java - 正则表达式 Java。为什么要使用交集?

标签 java regex intersection

我取自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/

相关文章:

c# - 关键字之间带有空格的任何字符

Java 正则表达式 : how to find a short word inside a longer one

android - 检查 android.graphics.path 与自身的交集

python - 计算字符串中的常见字符 Python

java - 使用字符串变量作为 'if' 条件的一部分时出现问题

java - 从 Java 控制台应用程序公开 macOS Finder 中的文件

java - Spring Boot 和 Flyway : Clear database data before integration tests

Python - 使用 re.findall 中的\n 将列表写入文本文件

c++ - 初级 C++ : Transforming index-syntax into iterator-syntax

java - Linux 中 SOAP 请求的请求 xml 中的 UTF-8 编码