正则表达式和 OR 运算符没有在 Python 中分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13964986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:03:22  来源:igfitidea点击:

Regex and the OR operator without grouping in Python?

pythonregexregex-group

提问by pedram

Here are the cases. I'm looking for the following pattern in a log file.

以下是案例。我正在日志文件中寻找以下模式。

All strings are in the form of AB_Nor CDE_N. ABand CDEare fixed letters, followed by an underscore. Ncan be either 2 or 3 numbers.

所有字符串都采用AB_Nor的形式CDE_NABCDE是固定字母,后跟下划线。 N可以是 2 或 3 个数字。

I tried (AB|CDE)_\d{2,3}but that returns a group. I can't do \w{2,3}\d{2,3}because it has to be either ABor CDEand not ACor FEG. Omitting the parentheses breaks too. I am sure the solution is simple but I'm new to python and regex and can't figure this out.

我试过了,(AB|CDE)_\d{2,3}但这会返回一个组。我不能这样做,\w{2,3}\d{2,3}因为它必须是ABorCDE和 not ACor FEG。省略括号也会中断。我确信解决方案很简单,但我是 python 和 regex 的新手,无法弄清楚。

采纳答案by mattmc3

A ?:inside a parenthesis in a regex makes it non-capturing. Like so: (?:AB|CDE)_\d{2,3}

?:正则表达式中括号内的A使其无法捕获。像这样:(?:AB|CDE)_\d{2,3}

See docs here: http://docs.python.org/3/library/re.htmlAbout a third of the way through it goes over the non-capturing syntax.

请参阅此处的文档:http: //docs.python.org/3/library/re.html大约三分之一的内容介绍了非捕获语法。

回答by BrenBarn

The non-capturing group syntax is (?:...). So do (?:AB|CDE)_\d{2,3}. This is documentedalong with everything else.

非捕获组语法是(?:...). 也一样(?:AB|CDE)_\d{2,3}。这与其他所有内容一起记录