首页 > 解决方案 > 如何在正则表达式上指定不匹配的内容

问题描述

免责声明:此问题已重做,因此评论和答案可能看起来不相关。我道歉,但我这样做是为了一个更清晰、结构更好的问题。

假设给定字符串,我想在其中找到两个不同的组(名称),其中一组 A 满足条件 1,组 B 满足条件 2,但也满足条件 1。

举个例子:假设我有一个数学函数-

'[class.parameterA] * numpy.exp( [x]*module.constantA - constant_B/[x] ) + [parameter_B]'

- 我控制参数的值,但不控制常量的值。我想(通过使用re.findall())获取常量组和参数组。

>>> group1
['numpy.exp', 'module.constantA', 'constant_B']
>>> group2
['class.parameterA', 'x', 'x', 'parameter_B']

我知道对于这种特定情况,我不应该匹配numpy.exp,但为了问题的目的,我允许它匹配。

澄清一下,这个问题的目的是在正则表达式中寻找“忽略匹配{sequence}”的表示,并了解是否有可能在“仅满足条件 1”而不是“满足条件 1 而不是条件”中解决问题2" 方式,因此解决方案可以扩展到多个条件。请提供一个部分抽象的答案(不是对这个例子过于具体的答案)。

当然,过了一段时间,我只能为其中一个组找到部分解决方案(请参阅奖励),但非常欢迎任何其他明确的解决方案:

c1 = r'\w+\.?\w*' # forces alphanumeric variable structure
# c1 = r'[\w\.\(\)]*?' allows more freedom (can introduce function calls)
# at the cost of matching invalid names, like class..parameterA
c2 = r'(?<=\[)', r'(?=\])'

re_group2 = c2[0] + c1 + c2[1]

>>>> re.findall(re_group2, func)
['class.parameterA', 'x', 'x', 'parameter_B']

显然直观的括号否定不适用于group1,但我可能会错误地介绍它:

c1 = r'\w+\.?\w*'
nc2 = r'(?<!\[\w)', r'(?!\w\])' # condition 2 negation approach

re_group1 = nc2[0] + c1 + nc2[1]

>>> re.findall(re_group1, func)
['class.parameterA', 'numpy.exp', 'x', 'module.constantA',
'constant_B', 'x', 'parameter_B']

奖励:如果有,比如说module.submodule.constantA(超过 1 个点),正则表达式将如何变化?我想c1 = r'\w+(\.\w+)*',但它并没有达到我的预期。编辑:我需要使用非捕获组,因为我使用的是re.findall. 所以c1 = r'\w+(?:\.\w+)*'

标签: pythonregexregex-negation

解决方案


使用双倍findall会很棒。

import re
a = "rho_1 * x + R * [np.R] + rho_1 / x + R * [np.R]"

print(re.findall(r"\w+(?= \*| \/)",a))
print(re.findall("(?<=\[).*?(?=\])",a))
  1. 第 1 组
    • \w+ 匹配非字母数字字符,不包括“_”
    • (?= *| /) 字符串以*or 结尾/
  2. 第 2 组
    • (?<=[) 以[
    • .*? 尽可能少地匹配任何字符
    • (?=]) 以]

推荐阅读