天天看点

正则表达式实例

1,获取引号中的json字符串

正则表达式实例

@test  

    public void test_json(){  

        string input="\"normalprice\": \"{\"storageprice\":66,\"ud1price\":1,\"userperiodprice\":99}\",";  

        system.out.println(input);  

        string regex=".*\"\\{([^{}]*)\\}\".*";  

        string result=input.replaceall(regex, "$1");  

        system.out.println(result);  

    }  

正则表达式实例

2, 遇到的问题:

正则表达式实例

解决方法:

正则表达式实例

/*** 

     * ("normalprice": "{"storageprice":66,"ud1price":1,"userperiodprice":99}",) 

     * to<br> 

     * ("normalprice": {"storageprice":66,"ud1price":1,"userperiodprice":99},) 

     * @param input 

     * @param isstrict : 是否严格,true:[^{}]<br> 

     * false:.* 

     * @return 

     */  

    public static string getjsonfromquotes(string input,boolean isstrict){  

        string regexloose="\"(\\{.*\\})\"";  

        string regexstrict="\"(\\{[^{}]*\\})\"";  

        string regex=null;  

        if(isstrict){  

            regex=regexstrict;  

        }else{  

            regex=regexloose;  

        }  

        return result;  

参数说明:

isstrict:

(a)true:严格模式,"{和}" 之间不能包含{或}

(b)false:非严格模式:"{和}"之间可以包含任意字符

应用:

正则表达式实例

if (command.equals("unquotesjson")) {  

            string text = this.ta.gettext();  

            if(text!=null){  

                text=regexutil.getjsonfromquotes(text, false);  

                this.ta.settext(text);  

            }