Skip to main content
 首页 » 编程设计

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

2025年05月04日18zfyouxi

我正在尝试检查是否在打开的文档的特定行上执行了正则表达式,如果是,则添加到 计数变量加 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" 

请您参考如下方法:

绝对最好的方法是使用 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