首页 > 解决方案 > 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仅替换dddd但跳过aaabbccc

预期输出:acds

标签: javaregexstringpattern-matchingmatcher

解决方案


这可以在一个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

推荐阅读