如何在大海捞针中取代第n次出现?(Python)

2024-06-16 09:45:09 发布

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

我正试图在大海捞针。我只想通过re.sub公司(),但似乎无法找到适当的正则表达式来解决此问题。我试图适应:http://docstore.mik.ua/orelly/perl/cookbook/ch06_06.htm但我想在跨越多行时失败了。在

我目前的方法是一种迭代的方法,在每次突变之后从一开始就找到每个事件的位置。这是相当低效的,我想得到一些意见。谢谢!在


Tags: 方法rehttp事件公司docstoreperl意见
3条回答

像这样的正则表达式应该对你有帮助。虽然我不确定它有多有效:

#N=3   
re.sub(
  r'^((?:.*?mytexttoreplace){2}.*?)mytexttoreplace',
  '\1yourreplacementtext.', 
  'mystring',
  flags=re.DOTALL
)

DOTALL标志很重要。在

我想你是说re.sub。您可以传递一个函数并跟踪到目前为止它被调用的频率:

def replaceNthWith(n, replacement):
    def replace(match, c=[0]):
        c[0] += 1
        return replacement if c[0] == n else match.group(0)
    return replace

用法:

^{pr2}$

但这种方法感觉有点老套,也许还有更优雅的方法。在

{a1}

我为此苦苦挣扎了一段时间,但我找到了一个我认为非常适合Python的解决方案:

>>> def nth_matcher(n, replacement):
...     def alternate(n):
...         i=0
...         while True:
...             i += 1
...             yield i%n == 0
...     gen = alternate(n)
...     def match(m):
...         replace = gen.next()
...         if replace:
...             return replacement
...         else:
...             return m.group(0)
...     return match
...     
... 
>>> re.sub("([0-9])", nth_matcher(3, "X"), "1234567890")
'12X45X78X0'

编辑:匹配器由两部分组成:

  1. alternate(n)函数。这将返回一个generator,它返回一个无限序列True/False,其中每n个值都为True。把它想象成list(alternate(3)) == [False, False, True, False, False, True, False, ...]

  2. match(m)函数。这是传递给re.sub的函数:它获取alternate(n)gen.next())中的下一个值,如果是True,它将替换匹配的值;否则,它将保持不变(用自身替换它)。

我希望这足够清楚。如果我的解释不清楚,请说出来,我会改进的。在

相关问题 更多 >