【问题标题】:java pattern matches not workingjava模式匹配不起作用
【发布时间】:2015-08-02 12:07:31
【问题描述】:

我想从一个字符串中获取类名。例如public class hello extends jframe。然后我想得到hello作为类名。但是如果String是public class hello,我也想得到hello

我写了一个正则表达式,它工作正常。 see here online preview.

这是我的正则表达式

(public)*\s*class\s+(\S+)\s+

预览

如您所见,它可以工作..它捕获类名。 (红色 -> 第 2 组)

但在java中m.matches()返回false,因为整个字符串不匹配,而是一部分。所以根据this answer,我使用hitEnd()方法,但它也不起作用??当甚至字符串完全不匹配但部分匹配时,我如何捕获类名

String cstring = "public class hello extends jframe ";
Pattern classPattern = Pattern.compile("(public)*\\s*class\\s+(\\S+)\\s*");
Matcher m = classPattern.matcher(cstring);
m.matches();
if (m.hitEnd()) {
    System.out.println("found");
    String className = m.group(2);
    System.out.println(className);
}

输出什么都不是。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    见下面代码中的cmets和解释:

    String cstring = "public class hello extends jframe ";
    Pattern classPattern = Pattern.compile(".*?class\\s+(\\S+)\\s*"); // regex was changed a bit
    Matcher m = classPattern.matcher(cstring);
    //m.matches();  // <-- no need for that 
    if (m.find()) { // use find() instead of m.hitEnd()
        System.out.println("found");
        String className = m.group(1);
        System.out.println(className);
    }
    

    输出

    found
    hello
    

    基本上,我从正则表达式中删除了(public),并使用了“1”匹配组(零是整个表达式,以防匹配)。您的正则表达式也可以使用,但是您必须使用借调的匹配组,因为 (public) 将首先出现。

    除此之外,我还删除了不需要的m.matches(),并将m.hitEnd() 替换为m.find(),它应该用于迭代匹配的结果。

    【讨论】:

      【解决方案2】:

      您需要调用find() 以使引擎在尝试访问之前找到它的匹配项。

      String s  = "public class hello extends jframe";
      Pattern p = Pattern.compile("public\\s*class\\s+(\\S+)");
      Matcher m = p.matcher(s);
      if (m.find()) {
          System.out.println("found");
          String className = m.group(1);
          System.out.println(className);
      }
      

      Ideone Demo

      【讨论】:

      • 所以我不应该使用hitEnd,因为字符串不完全匹配,而是部分匹配模式
      • @whiletrue,不,你不应该
      【解决方案3】:

      试试if (m.find())

      public static void main(String[] args) throws Exception {
          String cstring = "public class hello extends jframe ";
          Pattern classPattern = Pattern.compile("(public)*\\s*class\\s+(\\S+)\\s*");
          Matcher m = classPattern.matcher(cstring);
      
          if (m.find()) {
              System.out.println("found");
              String className = m.group(2);
              System.out.println(className);
          }
      }
      

      结果:

      found
      hello
      

      此外,您的捕获组(\\S+) 将匹配任何可能导致无效类名的非空白字符。考虑将该捕获组更改为 ([a-zA-Z_$]\\w*) 以捕获有效的类名。

      【讨论】:

        猜你喜欢
        • 2013-07-20
        • 2012-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多