首页 > java 正则匹配

java 正则匹配

  @Test
  public void test() {
    Pattern pattern = Pattern.compile("\"(\\w+)\":\"(\\w+)\"");
    Matcher m = pattern.matcher("\"KEY\":\"VAL\"");
    m.group(1);
  }

请问这个正则为什么无法匹配. 脑子进猪油了,现在


    因为'\'和'"'(双引号)是需要要转义符的'\'的.像下面写就能行了.
    Pattern pattern = Pattern.compile("\\\"(\\w+)\\\":\\\"(\\w+)\\\"");
    Matcher m = pattern.matcher("\"KEY\":\"VAL\"");
    //m.group(1);
    if(m.find()){
        System.out.println(m.group(1));
    }
    

你的表达式没什么问题,只是你得先调m.find()再取m.group(1)

【热门文章】
【热门文章】