java8 正则匹配字符串:第二次出现前面的内容
你可以使用反向引用来匹配第二次出现前面的内容。在正则表达式中,可以使用(\w+)来匹配一个或多个字母数字字符,并将其捕获到一个分组中。然后使用\1来引用第一个捕获的分组,以匹配第二次出现前面的内容。下面是一个示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String input = "Hello World Hello World";
String regex = "(\\w+)\\W+\\1";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Match: " + matcher.group());
System.out.println("First occurrence: " + matcher.group(1));
}
}
}
在上面的示例中,我们使用正则表达式(\w+)\W+\1来匹配第二次出现前面的内容。\w+匹配一个或多个字母数字字符,\W+匹配一个或多个非字母数字字符,\1引用第一个捕获的分组。输出将是:
Match: Hello World
First occurrence: Hello
请注意,上面的示例只匹配第二次出现前面的内容。如果你想匹配所有重复的内容,可以使用while循环遍历所有匹配项
原文地址: https://www.cveoy.top/t/topic/hORl 著作权归作者所有。请勿转载和采集!