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.