只有当re()匹配时,才对字符串执行进一步的步骤



我有一系列字符串。其中一些匹配特定的正则表达式。如果(并且只有当(他们这样做了,我想基于正则表达式进行替换,然后进行一些进一步的处理。

可以天真地写成:

for string in stringlist:
if re.search(r'^A d+ (?:1 d+ )?B d+ Cd+ ', string):
reprocess(re.sub(r'^(A d+ (?:1 d+ )B d+ Cd+) (.*)$', r'2 1', string))

但是,将正则表达式运行两次似乎很愚蠢。

我不能只执行re.sub(),因为如果正则表达式不匹配,它仍然会返回一个字符串结果,这只是原始的未更改字符串,如果不匹配,我不希望再处理。我想我可以将它与原始字符串进行比较,但这似乎很愚蠢。

如果re.sub()无法替换任何内容,我希望有一种方法可以让它返回一个假值。

我能想到的最好的东西是:

for string in stringlist:
(subst, replaced) = re.subn(r'^(A d+ (?:1 d+ )B d+ Cd+) (.*)$', r'2 1', string)
if replaced:
reprocess(subst)

这看起来冗长而草率。

难道没有更好的、更像蟒蛇的方式吗?

我会这样做:

import re
my_pattern = r'^(A d+ (?:1 d+ )B d+ Cd+) (.*)$'
compiled = re.compile(my_pattern). # This is a re.Pattern object
def replace_function(match_obj):
a = match_obj.group(1)
b = match_obj.group(2)
if a is not None and b is not None:
return f"{b} {a}"
else:
return None

for s in stringlist:
replaced = compiled.sub(replace_function, s)  # All the same methods are available, with the pattern compiled
if replaced:
reprocess(subst)

如果你想要,你甚至可以把你的再处理逻辑放在函数中

最新更新