是否可以减去字符类中的匹配字符?
Java docs有关于带减法的字符类的例子:
[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
组中。
这通过使用否定前瞻来确保第一个字符组中第二个字符之后的字符是不同的字符。
关于java - 模式 : how subtract matched character in character class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9174006/