只是遇到了一些Java正则表达式的问题。
我有一个程序可以读取HTML文件并替换@VR@字符中的任何字符串,即@VR@Test1 2 3 4@VR@
然而,我的问题是,如果一行包含两个以上由@VR@括起来的字符串,它就不匹配它们。它会将句子中最左边的“VR”与最右边的“VR”相匹配,从而获取介于两者之间的任何内容。
例如:
<a href="@VR@URL-GOES-HERE@VR@" target="_blank" style="color:#f4f3f1; text-decoration:none;" title="ContactUs">@VR@Google@VR@</a> 我的代码将匹配
URL-GOES-HERE@VR@" target="_blank" style="color:#f4f3f1; text-decoration:none;" title="ContactUs">@VR@Google以下是我的Java代码。如果你能帮我解决这个问题,我将不胜感激:
Pattern p = Pattern.compile("@VR@.*@VR@");
Matcher m;
Scanner scanner = new Scanner(htmlContent);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
m = p.matcher(line);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String match_found = m.group().replaceAll("@VR@", "");
System.out.println("group: " + match_found);
}
}我尝试用m.group(0)和m.group(1)替换m.group(),但是没有结果。此外,m.groupCount()总是返回零,即使像上面的例子中有两个匹配也是如此。
谢谢,您的帮助我们将不胜感激。
发布于 2015-01-20 07:27:54
您的问题是.*是“贪婪的”;它将尝试匹配尽可能长的子字符串,同时仍然让整个表达式匹配。因此,例如,在@VR@ 1 @VR@ 2 @VR@ 3 @VR@中,它将与1 @VR@ 2 @VR@ 3匹配。
最简单的解决方法是通过将*更改为*?,使其“非贪婪”(尽可能少地匹配,同时仍然让表达式匹配)
Pattern p = Pattern.compile("@VR@.*?@VR@");m.groupCount()总是返回零,即使像上面的例子一样有两个匹配项。
这是因为m.groupCount()返回底层模式中捕获组的数量(带括号的子表达式,其对应的匹配子字符串使用m.group(1)和m.group(2)等检索)。在您的示例中,您的模式没有捕获组,因此m.groupCount()返回0。
发布于 2015-01-20 07:28:14
您可以尝试正则表达式:
@VR@(((?!@VR@).)+)@VR@演示:
private static final Pattern REGEX_PATTERN =
Pattern.compile("@VR@(((?!@VR@).)+)@VR@");
public static void main(String[] args) {
String input = "<a href=\"@VR@URL-GOES-HERE@VR@\" target=\"_blank\" style=\"color:#f4f3f1; text-decoration:none;\" title=\"ContactUs\">@VR@Google@VR@</a> ";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("$1")
); // prints "<a href="URL-GOES-HERE" target="_blank" style="color:#f4f3f1; text-decoration:none;" title="ContactUs">Google</a> "
}https://stackoverflow.com/questions/28035232
复制相似问题