【发布时间】:2018-05-10 14:43:05
【问题描述】:
以下是我的 Java 代码,用于删除所有匹配的相邻字母对,但 Java Matcher 类出现了一些问题。
我的方法
我正在尝试在输入中查找所有连续重复的字符,例如
aaa, bb, ccc, ddd
接下来将奇数长度匹配替换为最后匹配的模式,将偶数长度匹配替换为"",即
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
【问题讨论】:
-
Expected Output : acds应该是acs因为d在偶数位置。 -
它不是在位置上,而是在匹配模式的长度上 - 偶数或奇数。 'd'-s 连续重复的子串长度为 3,为奇数,应替换为组 'd'
-
代码跳过了前三个模式,只替换了最后一个匹配项。这就是我面临的问题。因为我只调用了一次 m.find(),然后我调用了 m.group(i),这也不是我的期望
标签: java regex string pattern-matching matcher