【问题标题】:Non greedy match of .* with ^.* 与 ^ 的非贪婪匹配
【发布时间】:2017-10-16 08:24:55
【问题描述】:

给定字符串:

s = "Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>"

如何将^f('y')[f('x').get()]^^f('barbar')^ 替换为字符串,例如PLACEXHOLDER?

想要的输出是:

Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>

我尝试过re.sub('\^.*\^', 'PLACEXHOLDER', s),但.* 很贪心,它匹配^f('y')[f('x').get()]^? and ^f('barbar')^ 并输出:

你为什么把一个 PLACEXHOLDER

可能有多个未知数字的子字符串由\^ 编码,因此不需要硬编码:

re.sub('(\^.+\^).*(\^.*\^)', 'PLACEXHOLDER', s)

【问题讨论】:

    标签: python regex placeholder regex-greedy non-greedy


    【解决方案1】:

    如果你在星号后面加一个问号,它会使其不贪心。

    \^.*?\^
    

    http://www.regexpal.com/?fam=97647

    Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>
    

    正确替换为

    Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2011-12-10
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2011-08-29
      相关资源
      最近更新 更多