当前位置: 代码迷 >> J2EE >> 菜鸟求请问java正则表达式,匹配不成对的把该字符初始化null,求指点,多谢了
  详细解决方案

菜鸟求请问java正则表达式,匹配不成对的把该字符初始化null,求指点,多谢了

热度:1   发布时间:2016-04-17 23:21:13.0
初学者求请教java正则表达式,匹配不成对的把该字符初始化null,求指点,谢谢了
判断输入的字符串是否符合这种格式{"":"","":[],[]}  或者{"":{}}  如果不是就把输入的字符串置空
例如
String  str="sasasas";
str不符合格式
输出
str=null;
String test="asasasascc{"a":{}}";
输出asasasascc{"a":{}}
初级问题   求指点怎么写

------解决思路----------------------
jdk自带的正则表达式验证

Pattern pattern = Pattern.compile(regex) // 参数是正则表达式

Matcher matcher = pattern.matcher(input) // 参数是要匹配的字符串

boolean b = matcher.matches(); 
------解决思路----------------------

    public static void main(String[] args) {
        // {"":"","":[],[]} 或者{"":{}}
        Pattern p1 = Pattern
                .compile("(\\{\".*?\"\\:\".*?\",\"\".*?\\:\\[.*?\\],\\[.*?\\]\\})(\\{\".*?\"\\:\\{.*?\\}})");

        String str = "sasasas";
        String test = "asasasascc{\"a\":{}}";
        String test2 = "asasasascc{\"\":{asdf}}";

        Matcher m = p1.matcher(str);
        if (!m.find(1) && !m.find(2)) {
            str = null;
        }
        System.out.println(str);

        Matcher m2 = p1.matcher(test);
        if (!m2.find(1) && m2.find(2)) {
            test = null;
        }
        System.out.println(test);
        
        Matcher m3 = p1.matcher(test2);
        if (!m3.find(1) && m3.find(2)) {
            test2 = null;
        }
        System.out.println(test2);
    }

这个符合要求不