Python:在捕获regex中省略内容

2024-10-01 04:49:58 发布

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

我正在使用Python 2.x中的正则表达式捕捉缩写的子集。下面的文本中出现了几个这样的缩写:

# text                                    # desired capture
The certolizumab pegol (Cmzia, CZP)...      'CZP'
The drug 6-mercatopureine (6-mp) ...        '6-mp'
The merits of 5-Asasdfdsf (5-ASA) ...       '5-ASA'    

在第一个示例中,我希望返回结果CZP,而忽略{}。在

这是我以前的正则表达式,它是匹配(6-mp)和{}等情况所必需的:

^{pr2}$

以下是我为处理上述案件所做的补充:

\S*\s+[A-Z-0-9]+  # I only want to capture the '[A-Z-0-9]+'

我尝试过使用以下正则表达式(我尝试将感兴趣的部分加粗,这样就不会与上下文混淆,但这似乎不起作用):

# in p1, I add the pattern to the list, separated by '|'
>>> p1 = re.compile(r'\((\S*[A-Z-0-9]\S*|\S*\s+[A-Z-0-9]+)\)')
>>> p1.findall('The certolizumab pegol (Cmzia, CZP)')
['Cmzia, CZP']

# in p2, I use a broad non-capturing group, enclosing the desired captured expressions in parentheses
>>> p2 = re.compile(r'\((?:(\S*[A-Z-0-9]\S*)|\S*\s+([A-Z-0-9]+))\)')
>>> p2.findall('The certolizumab pegol (Cmzia, CZP)')                           
[('', '', 'CZP')] 

# this is an addition to the original post
# demonstrates that the non-capturing expression doesn't prevent capture of the section \S*\s+
>>> p3 = re.compile(r'\((\S*[A-Z-0-9]\S*|(?:\S*\s+)[A-Z-0-9]+)\)')
>>> p3.findall('The certolizumab pegol (Cmzia, CZP)')                           
['Cmzia, CZP']

理想情况下,我想要输出CZPp1返回太多,因为我想排除与Cmzia,对应的\S*\s+。关于p2,我知道我可以很容易地操作输出以匹配我想要的输出,但是我想知道是否有方法可以修改regex来处理它。在

谢谢,如果你需要更多的细节/说明请告诉我。在

编辑:

我仍然希望正则表达式从regex的第一个/原始部分捕获6-mp和{}。在

编辑2:

这是包括在上面,但把它放在一个地方,并总结我的问题。在

pattern = r'???'
p = re.compile(pattern)
p.findall('Stuff stuff (Cmzia, CZP) stuff stuff (5-ASA) (6-mp) stuff...')
['CZP','5-ASA','6-mp']

Tags: therempcapturep2compilestuffp1
3条回答

我不太明白您想要什么,但我在对应于'CZP'的部分加了另一个匹配的括号,并使外部组不匹配,得到如下结果:

>>> p3 = re.compile(r'\((?:\S*[A-Z-0-9]\S*|[A-Z-0-9]* [A-Z-0-9]*|(?:\S*\s+)([A-Z-0-9]+))\)')
>>> p3.findall('The certolizumab pegol (Cmzia, CZP)')
['CZP']

如果我没看错,括号内可能有一到两个逗号分隔的值。如果是两个,你只想抓住第二个。试试这个:

p = re.compile(r'\((?:[^,)]+,\s*)?([A-Za-z0-9-]+)\)')

在开始paren之后,(?:[^,)]+,\s*)?尝试匹配第一个值,它通过后面的逗号来标识第一个值。您并不真正关心第一个值是什么样子,只要其中没有任何逗号。但不能只使用[^,]+,因为在只有一个值的情况下,这会匹配太多。将paren添加到排除的字符列表中,使匹配保持在一组括号中。在

这是我找到的实现目标的最简单的正则表达式:

>>> p = "\((?:\S*,\s+)?(\S*)\)"
>>> s = "The cert pegol (Cmzia, CZP) some words (6-mp) and (5-ASA)"
>>> re.findall(p,s)
['CZP', '6-mp', '5-ASA']

更新

下一个更具限制性,但结果相同:

^{pr2}$

相关问题 更多 >