RegExpr 输出不正确

RegExpr output incorrect

我正在尝试从要使用匹配器匹配模式的字符串中获取所有输出,但是,我不确定字符串或我的模式是否正确。我试图将 (Server: switch) 作为第一个模式,在换行符之后依此类推,但是,正如我的输出所示,我只得到最后三个模式。我的输出如下,代码如下

found_m: Message: Mess                                                                                                                          
found_m: Token: null                                                                                                                            
found_m: Response: OK

这是我的代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

   public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String line = "Server: Switch\nMessage: Mess\nToken: null\nResponse: OK";
      String pattern = "([\w]+): ([^\n]+)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
        while(m.find()) {
            System.out.println("found_m: " + m.group());
        }
      }else {
         System.out.println("NO MATCH");
      }
   }
}

是我的字符串行不正确还是我没有做正则表达式的字符串模式错误?

提前致谢。

您的正则表达式几乎正确。

问题是您调用了 find 两次:第一次在 if 条件下,然后在 while.

下再次调用

您可以使用 do-while 循环代替:

if (m.find( )) {
   do {
        System.out.println("found_m: " + m.group());
   } while(m.find());
} else {
    System.out.println("NO MATCH");
}

对于正则表达式部分,您可以稍作修正后使用:

final String pattern = "(\w+): ([^\n]+)";

或者如果您不需要 2 个捕获组,则使用:

final String pattern = "\w+: [^\n]+";

因为不需要在\w+

周围使用字符class

我不熟悉 Java,但是这个正则表达式模式应该可以捕获每个组并进行匹配。

([\w]+): (\w+)(?:(?:[\][n])|$)

它基本上是说捕获冒号和 space 之后的单词,然后捕获 \n 或字符串结尾之前的下一个单词。

祝你好运。