我取自this关于 Java 正则表达式的 Oracle 教程,以下位:
Intersections
To create a single character class matching only the characters common to all of its nested classes, use &&, as in [0-9&&[345]]. This particular intersection creates a single character class matching only the numbers common to both character classes: 3, 4, and 5.
Enter your regex: [0-9&&[345]] Enter input string to search: 3 I found the text "3" starting at index 0 and ending at index 1.
为什么会有用?我的意思是,如果一个人只想图案化 345,为什么不只是 [345] 而不是“交集”?
提前致谢。
最佳答案
让我们考虑一个简单的问题:匹配字符串中的英文辅音。列出所有辅音(或范围列表)是一种方式:
[B-DF-HJ-NP-TV-Zb-df-hj-np-tv-z]
另一种方法是使用环视:
(?=[A-Za-z])[^AEIOUaeiou]
(?![AEIOUaeiou])[A-Za-z]
不确定是否有任何其他方法可以在不使用字符类交集的情况下做到这一点。
字符类交集解决方案(Java):
[A-Za-z&&[^AEIOUaeiou]]
对于.NET,没有交集,但是有字符类减法:
[A-Za-z-[AEIOUaeiou]]
我不知道实现细节,但如果字符类交集/减法比使用环视更快,我不会感到惊讶,如果字符类操作不可用,这是最干净的选择。
另一种可能的用法是当你有一个预建的角色类并且你想从中删除一些角色时。我遇到的一种可能适用类交集的情况是匹配所有空白字符,换行符除外。
@beerbajay 评论的另一个可能的用例:
I think the built-in character classes are the main use case, e.g.
[\p{InGreek}&&\p{Ll}]
for lowercase Greek letters.
关于java - 正则表达式 Java。为什么要使用交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930181/