我可以在正则表达式中使用OR而不捕获其中包含的内容吗? [英] Can I use an OR in regex without capturing what's enclosed?

查看:97
本文介绍了我可以在正则表达式中使用OR而不捕获其中包含的内容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rubular.com 构建我的正则表达式,其文档描述了以下内容:

I'm using rubular.com to build my regex, and their documentation describes the following:

(...)   Capture everything enclosed
(a|b)   a or b

如何使用OR表达式而不捕获其中的内容?例如,假设我要捕获 ac或 bc。我不能使用正则表达式

How can I use an OR expression without capturing what's in it? For example, say I want to capture either "ac" or "bc". I can't use the regex

(a|b)(c)

对吗?从那时起,我在一个组中捕获了 a或 b,而在另一组中捕获了 c,但并不相同。我知道我可以过滤捕获的结果,但这似乎需要更多工作...

right? Since then I capture either "a" or "b" in one group and "c" in another, not the same. I know I can filter through the captured results, but that seems like more work...

我错过了明显的东西吗?

Am I missing something obvious? I'm using this in Java, if that is pertinent.

推荐答案

根据正则表达式实现,您可以使用所谓的非捕获组,语法为(?:…)

Depending on the regular expression implementation you can use so called non-capturing groups with the syntax (?:…):

((?:a|b)c)

此处(?: a | b)是一个群组,但您无法引用其匹配项。因此,您只能引用((?: a | b)c)的匹配项,即 ac bc

Here (?:a|b) is a group but you cannot reference its match. So you can only reference the match of ((?:a|b)c) that is either ac or bc.

这篇关于我可以在正则表达式中使用OR而不捕获其中包含的内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆