【问题标题】:String replace with re sub matching the exact string [duplicate]字符串替换为与确切字符串匹配的 re sub [重复]
【发布时间】:2017-01-18 20:30:53
【问题描述】:

我想更改段落第一行中的字符串 foo 而不更改另一行。我已经使用模式 ^ 和 $ 来匹配我在 perl 中所做的确切字符串,但仍然没有运气。请帮忙。

我的代码:

input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print input_file

所以,我期待这样的结果:

bar afooa

提前致谢

【问题讨论】:

  • 你能找出 re.sub 吗?

标签: python regex


【解决方案1】:

您的正则表达式当前是r'^foo$',它基本上与字符串“foo”匹配仅。

如果您只是将其更改为 r'^foo',只要在字符串的开头找到“foo”,它就会匹配,但与您之前的模式不同,它不关心 foo 后面的内容。

这是一个例子:

input_file = "foo afooa"
input_file = re.sub(r'^foo', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo', 'bar', input_file2)
print input_file
print input_file2

输出:

bar afooa   
barb afooa

现在,如果您不想匹配字符串的一部分,而是在行首匹配整个字符串 'foo',那么您需要添加边界 '\b' 匹配,如下所示:

input_file = "foo afooa"
input_file = re.sub(r'^foo\b', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo\b', 'bar', input_file2)
print input_file
print input_file2

输出:

bar afooa
foob afooa

或者,如果您只想替换第一次出现的完整单词“foo”,请使用@DineshPundkar 建议的模式,并将替换次数限制为 1,就像刚才提到的 @Tuan333。

因此,在这种情况下,您的代码将如下所示:

input_file = "a foo afooa foo bazfooz"
input_file = re.sub(r'\bfoo\b', 'bar', input_file, 1)
print input_file

输出:

a bar afooa foo bazfooz

【讨论】:

    【解决方案2】:

    从doc,您可以将count = 1 的re.sub() 设置为仅更改模式的第一次出现。此外,删除^ 和$,因为您不想搜索仅包含单词foo 的整行。示例代码:

    import re; 
    input_file = "foo afooa"; 
    input_file = re.sub(r'foo', 'bar', input_file, count = 1); 
    print input_file;
    

    【讨论】:

      【解决方案3】:

      用 \b 代替 ^ 和 $ 来匹配边界。

      >>> a="foo afooa"
      >>> b= re.sub(r"\bfoo\b",'bar',a)
      >>> b
      'bar afooa'
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 2010-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        相关资源
        最近更新 更多