java 中的 REGEX 用于提取字符串中的连续重复字符
REGEX in java for extracting consecutive duplicate characters in a string
问题:打印 字符串中仅连续 个字符两次(不多)。
示例:
1)“aaabbaa”:b 和 a
2)“aabbaa”:a 和 b 和 a
3)“阿爸”:b
我试过的代码:
String str = "aabbbbcccd";
模式 p = Pattern.compile("(\w){2}");
匹配器 m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
输出:
a
b
b
c
d
虽然,所需的输出是
一个
d
后记
由于我最近开始使用正则表达式,如果回答者能解释一下,我将不胜感激
正则表达式使用简单(尤其是量词和组)。
这个问题没有单一的普通正则表达式解决方案,因为你需要一个内部有反向引用的回顾,Java 正则表达式引擎不支持。
您可以做的是获取所有 (\w)+
个匹配项,然后使用常见的字符串方法检查它们的长度:
String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\w)\1+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group().length() == 2) System.out.println(matcher.group(1));
}
(参见 Java demo)或者您可以匹配 3 次或更多次重复或仅重复 2 次并且仅在第 2 组匹配时才获取匹配项:
String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\w)\1{2,}|(\w)\2");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group(2) != null)
System.out.println(matcher.group(2));
}
参见 this Java demo。 正则表达式详细信息:
(\w){2,}
- 一个单词 char 和在 之后出现两次或更多次相同的 char
|
- 或
(\w)
- 一个单词字符和紧跟其后的相同字符。
问题:打印 字符串中仅连续 个字符两次(不多)。
示例:
1)“aaabbaa”:b 和 a
2)“aabbaa”:a 和 b 和 a
3)“阿爸”:b
我试过的代码:
String str = "aabbbbcccd";
模式 p = Pattern.compile("(\w){2}");
匹配器 m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
输出:
a
b
b
c
d
虽然,所需的输出是
一个
d
后记
由于我最近开始使用正则表达式,如果回答者能解释一下,我将不胜感激
正则表达式使用简单(尤其是量词和组)。
这个问题没有单一的普通正则表达式解决方案,因为你需要一个内部有反向引用的回顾,Java 正则表达式引擎不支持。
您可以做的是获取所有 (\w)+
个匹配项,然后使用常见的字符串方法检查它们的长度:
String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\w)\1+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group().length() == 2) System.out.println(matcher.group(1));
}
(参见 Java demo)或者您可以匹配 3 次或更多次重复或仅重复 2 次并且仅在第 2 组匹配时才获取匹配项:
String s = "aaabbaa";
Pattern pattern = Pattern.compile("(\w)\1{2,}|(\w)\2");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group(2) != null)
System.out.println(matcher.group(2));
}
参见 this Java demo。 正则表达式详细信息:
(\w){2,}
- 一个单词 char 和在 之后出现两次或更多次相同的 char
|
- 或(\w)
- 一个单词字符和紧跟其后的相同字符。