正则表达式中的圆括号有什么区别?

2024-10-01 07:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在浏览pythonchallenge.com,并且正在尝试制作一个代码来搜索一个小写字母,它的两边正好有三个大写字母。然后我就被困在试图为它做一个正则表达式。这就是我尝试过的:

import re
#text is in https://pastebin.com/pAFrenWN since it is too long
p = re.compile("[^A-Z]+[A-Z]{3}[a-z][A-Z]{3}[^A-Z]+")
print("".join(p.findall(text)))

这就是我得到的: dqiqnlqslidbzeoekiveyjxwazadnmczqewaebzutklyngoucndehsbjgsgnkoixdbfhdxjvlgzvme公司 gZAGiLQZxjvCJAsACFlgfe公司 qKWGtIDCjn公司

后来我搜索了这个解决方案,它有一个正则表达式:

p = re.compile("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+")

所以[a-z]周围有一个括号,我不知道它有什么区别。我想解释一下


Tags: 代码textinhttpsimportrecomis
1条回答
网友
1楼 · 发布于 2024-10-01 07:51:30

Use Parentheses for Grouping and Capturing By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

https://www.regular-expressions.info/brackets.html

基本上,regex引擎可以找到与整个搜索模式匹配的字符串列表,并返回()中的部分

相关问题 更多 >