java - Java Regex Matcher 跳过匹配项
问题描述
下面是我的 Java 代码,用于删除所有匹配的相邻字母对,但我遇到了 Java Matcher 类的一些问题。
我的方法
我试图在输入中找到所有连续的重复字符,例如
aaa, bb, ccc, ddd
接下来用最后匹配的模式替换奇数长度匹配,用""
ie替换偶数长度匹配
aaa -> a
bb -> ""
ccc -> c
ddd -> d
s has single occurrence, so it's not matched by the regex pattern and excluded from the substitution
我呼吁Matcher.appendReplacement
根据组长度(偶数或奇数)有条件地替换输入中匹配的模式。
代码:
public static void main(String[] args) {
String s = "aaabbcccddds";
int i=0;
StringBuffer output = new StringBuffer();
Pattern repeatedChars = Pattern.compile("([a-z])\\1+");
Matcher m = repeatedChars.matcher(s);
while(m.find()) {
if(m.group(i).length()%2==0)
m.appendReplacement(output, "");
else
m.appendReplacement(output, "$1");
i++;
}
m.appendTail(output);
System.out.println(output);
}
输入 :aaabbcccddds
实际输出:(aaabbcccds
仅替换ddd
为d
但跳过aaa
,bb
和ccc
)
预期输出:acds
解决方案
这可以在一个replaceAll
调用中完成,如下所示:
String repl = str.replaceAll( "(?:(.)\\1)+", "" );
正则表达式(?:(.)\\1)+
匹配所有出现的偶数重复并将其替换为空字符串,这样我们就得到了奇数重复的第一个字符。
使用Pattern
和的代码Matcher
:
final Pattern p = Pattern.compile( "(?:(.)\\1)+" );
Matcher m = p.matcher( "aaabbcccddds" );
String repl = m.replaceAll( "" );
//=> acds
推荐阅读
- python-3.x - Selenium - 通过链接文本查找元素
- java - 游戏一直在崩溃,甚至没有进入奥利奥的启动画面
- batch-file - 使用 WMIC /APPEND 获取 PC 规格
- sql - SQL | 将商店现金与银行现金匹配
- java - 使用动态方向禁用屏幕旋转
- javascript - 表单未更新动态 html 表的行数
- javascript - RabbitMQ:上一个完成后消费item
- angular - 使用角度材料以角度在两个表之间传输行数据
- ssms-2014 - 简单表中的最大字符长度已更改。为什么?
- jquery - 如何使用 Jquery 在不同的 div 中显示月份选择器