Java 模式:如何在字符类中减去匹配字符?

Java 模式:如何在字符类中减去匹配字符?,java,regex,Java,Regex,可以在字符类中减去匹配的字符吗 有关于减法字符类的示例: [a-z&&[^bc]] - a through z, except for b and c: [ad-z] (subtraction) [a-z&&[^m-p]] - a through z, and not m through p: [a-lq-z](subtraction) 我想写一个模式,它匹配两对单词字符,当两对字符不相同时: 1) "aaaa123" - should NOT mat

可以在字符类中减去匹配的字符吗

有关于减法字符类的示例:

[a-z&&[^bc]]    - a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]   - a through z, and not m through p: [a-lq-z](subtraction)
我想写一个模式,它匹配两对单词字符,当两对字符不相同时:

1) "aaaa123" - should NOT match
2) "aabb123" - should match "aabb" part
3) "aa--123" - should NOT match
我通过以下模式接近成功:

([\w])\1([\w])\2
当然,它在案例1中不起作用,所以我需要减去第一组的匹配项。但当我尝试这样做时:

Pattern p = Pattern.compile("([\\w])\\1([\\w&&[^\\1]])\\2");
我得到一个例外:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 17
([\w])\1([\w&&[^\1]])\2
                 ^
    at java.util.regex.Pattern.error(Pattern.java:1713)
因此,它似乎不适用于组,而只适用于列出特定字符。以下模式编译时没有问题:

Pattern p = Pattern.compile("([\\w])\\1([\\w&&[^a]])\\2");
有没有其他方法来编写这种模式?

使用

Pattern p = Pattern.compile("((\\w)\\2(?!\\2))((\\w)\\4)");
您的字符将分组为
1
3


这是通过使用负前瞻来实现的,以确保第一个字符组中第二个字符后面的字符是不同的字符。

您使用的作业工具错误。务必使用正则表达式来检测字符对,但您可以使用
=
以测试对中的字符是否相同。说真的,没有理由用正则表达式做任何事情——它会产生不可读、不可移植的代码,除了“看起来很酷”之外,不会给您带来任何好处。

试试这个

String regex = "(\\w)\\1(?!\\1)(\\w)\\2";
Pattern pattern = Pattern.compile(regex);
(?!\\1)
是一个,它确保
\\1
的内容不在后面

我的测试代码

String s1 = "aaaa123";
String s2 = "aabb123";
String s3 = "aa--123";
String s4 = "123ccdd";

String[] s = { s1, s2, s3, s4 };
String regex = "(\\w)\\1(?!\\1)(\\w)\\2";

for(String a : s) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(a);

    if (matcher.find())
        System.out.println(a + " ==> Success");
    else
        System.out.println(a + " ==> Failure");
}
输出

aaaa123==>故障
aabb123==>成功
aa--123==>故障
123ccdd==>成功


@Kilian:这个模式只是许多匹配字符串部分的模式之一(也有很多简单的模式)——所以这不仅仅是为了像你们说的“酷”——系统迭代模式并匹配它们。。。如果我按照你建议的方式去做,我会有更“不酷”的解决方案,因为我需要为一个或另一个案例添加自定义
ifs
。@flesk:很好,+1来自我!:)