假设一个给定的字符串,我想在其中找到两个不同的组(名称),其中一组 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']
我知道对于这种特定情况,我不应该 match numpy.exp,但是为了问题的目的,我允许它匹配。
澄清一下,这个问题旨在在正则表达式中寻找“忽略匹配{序列}”的表示,并了解是否有可能在“仅满足条件 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+)*'。
收到一只叮咚
相关分类