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