在正则表达式中,可以使用括号来分组多个标记,并使用反向引用来确保两个标记始终匹配。下面是一个使用括号和反向引用的示例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String input = "This is a sample text with matching tags content .";
// 创建正则表达式模式
String patternString = "<(\\w+)>.*?\\1>";
Pattern pattern = Pattern.compile(patternString);
// 创建Matcher对象,并进行匹配
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String match = matcher.group();
System.out.println("Match: " + match);
}
}
}
在上面的示例中,正则表达式模式<(\\w+)>.*?\\1>
使用了括号和反向引用。括号将\\w+
捕获为一个分组,并使用\\1
来引用这个分组。
运行上述代码将输出:
Match: content
这表明正则表达式成功匹配了带有匹配标记的文本。