加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式java.为何使用十字路口

发布时间:2020-12-14 05:49:53 所属栏目:百科 来源:网络整理
导读:我已经从 java regex上的 this 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 singl
我已经从 java regex上的 this 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读