我正在尝试在 Java 中的字符串中查找特定单词。我开发了一个函数,旨在返回找到的字符串。这就是我现在写的:
public static String getValueByregexExpr (String str, String regexExpr) {
Pattern regex = Pattern.compile (regexExpr, Pattern.DOTALL);
Matcher matcher1 = regex.matcher (str);
if (matcher1.find ()) {
if (matcher1.groupCount () != 0 && matcher1.group (1) != null) {
for (int i = 0; i <= matcher1.groupCount (); i++) {
System.out.println ("matcher " + i + " for regex " + regexExpr + "= " + matcher1.group (i));
}
return matcher1.group (1);
}
return regexExpr;
}
return null;
}
我的问题如下,我希望找到一个正则表达式,能够用我要查找的单词填充组(1)。但现在这段代码:
public static void main (String[] args) {
String str = "HELLO_WORLD_123456 TEst";
System.out.println ("First test");
String regex1 = ".*WORLD.*";
String matchedString = Util.getValueByregexExpr (str, regex1);
//Here, I want to obtain matchedString = WORLD
if (matchedString == null) {
System.out.println ("matchedString null");
} else if (matchedString.equals (regex1)) {
System.out.println ("String found but empty group(1)");
} else {
System.out.println ("Result : " + matchedString);
}
//Here, I want to obtain matchedString = WORLD_123456
System.out.println ("\nSecond test");
String regex2 = "WORLD_([^_]+)";
matchedString = Util.getValueByregexExpr (str, regex2);
if (matchedString == null) {
System.out.println ("regex " + regex2 + " matchedString null");
} else if (matchedString == regex2) {
System.out.println ("regex " + regex2 + " String found but empty group(1)");
} else {
System.out.println ("regex " + regex2 + " Result : " + matchedString);
}
}
给我输出:
First test:
regex .*WORLD.* String found but empty group(1)
Second test:
matcher 0 for regex WORLD_([^_]+)= WORLD_123456
matcher 1 for regex WORLD_([^_]+)= 123456
regex WORLD_([^_]+) Result : 123456
首先,有没有正则表达式可以返回: - 第一次测试的世界 - 第二次测试的 WORLD_123456
第二,我一开始就想,只要你只有一个结果,每个结果都会被设置到组(1)中。但鉴于测试 2 的结果,我显然错了。有人可以给我更多相关信息吗?
谢谢您的帮助。
要修复第一个,只需添加捕获组:
String regex1 = ".*(WORLD).*";
要解决第二个问题,请向字符类添加空格:
String regex2 = "(WORLD_[^_\\s]+)";
参见 演示
您的第一部分代码未按预期工作的主要原因是您的
getValueByregexExpr
正在检查缺少捕获组。
第二个返回用 ([^_]+)
正则表达式部分捕获的 Stirng 部分。
在正则表达式中,
()
内的所有内容都成为一个组。
纠正你
regex
。
String regex1 = ".*(WORLD).*";
String regex2 = "(WORLD_[^_\\s]+)";