Jos*_*hua 99 regex duplicates capture-group
我是一个正则表达式新手,我无法弄清楚如何编写一个能够"匹配"任何重复连续单词的正则表达式,例如:
在巴黎的的春天.
并非那是相关的.
你笑什么?是我的我的正则表达式不好?
是否有一个正则表达式将匹配上面的所有粗体字符串?
Gum*_*mbo 122
试试这个正则表达式:
\b(\w+)\s+\1\b
Run Code Online (Sandbox Code Playgroud)
这\b
是一个单词边界,并\1
引用第一组的捕获匹配.
Mik*_*ens 19
我相信这个正则表达式处理更多情况:
/(\b\S+\b)\s+\b\1\b/
Run Code Online (Sandbox Code Playgroud)
可以在这里找到很多测试字符串:http: //callumacrae.github.com/regex-tuesday/challenge1.html
小智 12
下面的表达式应该可以正常工作以找到任意数量的连续单词。匹配可以不区分大小写。
String regex = "\\b(\\w+)(\\s+\\1\\b)*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
// Check for subsequences of input that match the compiled pattern
while (m.find()) {
input = input.replaceAll(m.group(0), m.group(1));
}
Run Code Online (Sandbox Code Playgroud)
示例输入:再见再见再见再见
示例输出:再见
解释:
正则表达式:
\b : 单词边界的开始
\w+ :任意数量的单词字符
(\s+\1\b)* :任意数量的空格后跟匹配前一个单词并结束单词边界的单词。用 * 包裹的整个东西有助于找到不止一个重复。
分组:
m.group(0) : 应包含上述情况下的匹配组 Goodbye goodbye GooDbYe
m.group(1) :应包含上述情况下匹配模式的第一个单词再见
Replace 方法应将所有连续匹配的单词替换为单词的第一个实例。
试试这个正则表达式,它可以捕获 2 个或更多重复的单词,并且只留下一个单词。并且重复的单词甚至不必是连续的。
/\b(\w+)\b(?=.*?\b\1\b)/ig
Run Code Online (Sandbox Code Playgroud)
这里,\b
用于词边界,?=
用于正向前瞻,\1
用于反向引用。
尝试以下RE
()*再次重复
public static void main(String[] args) {
String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";// "/* Write a RegEx matching repeated words here. */";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
Scanner in = new Scanner(System.in);
int numSentences = Integer.parseInt(in.nextLine());
while (numSentences-- > 0) {
String input = in.nextLine();
Matcher m = p.matcher(input);
// Check for subsequences of input that match the compiled pattern
while (m.find()) {
input = input.replaceAll(m.group(0),m.group(1));
}
// Prints the modified sentence.
System.out.println(input);
}
in.close();
}
Run Code Online (Sandbox Code Playgroud)目前广泛使用的PCRE库可以处理这种情况(你不会达到的了与POSIX兼容的正则表达式引擎一样,虽然):
(\b\w+\b)\W+\1
Run Code Online (Sandbox Code Playgroud)