如何检查是否执行了Python中的RE

时间:2013-07-15 16:53:26

标签: python

我正在尝试检查是否在打开的文档的特定行上执行了正则表达式,然后再添加到 计数变量为1.如果计数超过2,我希望它停止。下面的代码是我到目前为止的。

for line in book:
    if count<=2:
            reg1 = re.sub(r'Some RE',r'Replaced with..',line)
            f.write(reg1)
            "if reg1 was Performed add to count variable by 1"

5 个答案:

答案 0 :(得分:4)

绝对最好的方法是使用re.subn()而不是re.sub()

re.subn()会返回一个元组(new_string, number_of_changes_made),因此非常适合您:

for line in book:
    if count<=2:
        reg1, num_of_changes = re.subn(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        if num_of_changes > 0:
            count += 1

答案 1 :(得分:2)

如果想要确定是否在线上进行了替换,那么这很简单:

count = 0
for line in book:
    if count<=2:
        reg1 = re.sub(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        count += int(reg1 == line)

答案 2 :(得分:1)

您可以将函数传递给re.sub作为替换值。这可以让你做这样的事情:(虽然简单的搜索然后子方法,而较慢的将更容易推理):

import re

class Counter(object):
    def __init__(self, start=0):
        self.value = start

    def incr(self):
        self.value += 1

book = """This is some long text
with the text 'Some RE' appearing twice:
Some RE see?
"""

def countRepl(replacement, counter):
    def replacer(matchobject):
        counter.incr()
        return replacement

    return replacer

counter = Counter(0)

print re.sub(r'Some RE', countRepl('Replaced with..', counter), book)

print counter.value

这会产生以下输出:

This is some long text
with the text 'Replaced with..' appearing twice:
Replaced with.. see?

2

答案 3 :(得分:0)

您可以将其与原始字符串进行比较,看它是否发生了变化:

for line in book:
    if count<=2:
        reg1 = re.sub(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        if line != reg1:
            count += 1

答案 4 :(得分:0)

subn将告诉你在行中进行了多少次替换,count参数将限制将尝试的替换次数。将它们组合在一起,即使在一行上有多个潜艇,您也会在两次替换后停止代码。

look_count = 2
for line in book:
    reg1, sub_count = re.subn(r'Some RE', r'Replaced with..', line,count=look_count)
    f.write(reg1)
    look_count -= sub_count
    if not look_count:
        break