正则表达式:仅查找单引号之外的匹配项

问题描述 投票:0回答:1

我目前有一个正则表达式,可以选择所有出现的

(
, 
);
:

(\s\()|(,\s)|(\),)|(\);)

但是,我一直在尝试找出一种方法,以便如果单引号之间有任何内容

'like this, for example'
,它将忽略上面列出的任何匹配项。尝试了许多不同的解决方案,但似乎没有一个对我有用。

有人知道我可以如何实现这项工作吗?谢谢!

python-3.x regex regex-lookarounds regex-group
1个回答
0
投票

您可以使用像

('[^']*')|(\s\()|(,\s)|(\),)|(\);)
这样的模式并过滤掉那些您不想要的子字符串

import re

p = r"('[^']*')|(\s\()|(,\s)|(\),)|(\);)"
s = """'like this, for example' ("""
print([m for match in re.findall(p, s) for m in match if m and not match[0].startswith("'")])

打印

['(']


注:

  • ('[^']*')
    是您要排除的部分。
© www.soinside.com 2019 - 2024. All rights reserved.