java - RegExpr 输出不正确

标签 java regex string pattern-matching regex-group

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

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");
      }
   }
}

我的字符串行是否不正确,或者我的字符串模式是否没有执行 regexpr 错误?

提前致谢。

最佳答案

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

问题是您调用了 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+ 周围使用字符类

关于java - RegExpr 输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530384/

相关文章:

javascript - 换行符及其在 Javascript 字符串连接中的效果

c++ - 从 'char' 到 'const char*' 的无效转换 [-fpermissive]

java - 使用两个 if 的半数组循环的时间复杂度与使用一个 if 的全数组循环的时间复杂度相同吗?

regex - PowerShell正则表达式在换行符附近不匹配

java - 如何为 BinaryTree<T> 类编写 left() 和 right() 方法

php - 如何使 preg_replace 仅替换匹配的*每个*字符中的第一个?

php - URL 的 filter_var 不正确

java - 是否可以使用字符串的内容来转换对象?

java - Hibernate 查询语法异常

java - 如何泛化我的界面