Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式问题-Can';t在同一行中匹配两个字符串_Java_Regex - Fatal编程技术网

Java正则表达式问题-Can';t在同一行中匹配两个字符串

Java正则表达式问题-Can';t在同一行中匹配两个字符串,java,regex,Java,Regex,只是在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-decorat

只是在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>    
这是我的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()始终返回零,即使有两个匹配项,如上面的示例所示


谢谢,非常感谢您的帮助。

您的问题是
*
是“贪婪的”;它将尝试匹配尽可能长的子字符串,同时仍让整个表达式匹配。因此,例如,在
@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。

您可以尝试使用正则表达式:

@VR@(((?!@VR@).)+)@VR@
演示:

private静态最终模式REGEX\u模式=
编译(“@VR@(((?!@VR@)。+)@VR@”);
公共静态void main(字符串[]args){
字符串输入=”;
System.out.println(
REGEX_PATTERN.matcher(输入).replaceAll($1)
);//打印件“”
}

你来这里是关于非贪婪的吗?试试
@VR@.*?@VR@
听到的
不在这里…=)谢谢,这就成功了!!
@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> "
}