Skip to main content
 首页 » 编程设计

python之正则表达式不过是写在匹配

2025年05月04日32lonelyxmas

在使用正则表达式时,我们通常(如果不是总是)使用它们来提取某种信息。我需要的是用其他值替换匹配值...

现在我正在做这个......

def getExpandedText(pattern, text, replaceValue): 
    """ 
        One liner... really ugly but it's only used in here. 
    """ 
 
    return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \ 
            text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):] 

所以如果我做某事喜欢

>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo") 
'hola aaaooobbb como estas?' 

它将 (...) 更改为 'ooo'。

你们知道我们是否可以使用 python 正则表达式来做到这一点吗?

非常感谢你们!!

请您参考如下方法:

sub (replacement, string[, count = 0]) 

sub返回通过用替换替换替换 string 中 RE 的最左边非重叠出现而获得的字符串。如果未找到模式,则返回未更改的字符串。

    p = re.compile( '(blue|white|red)') 
    >>> p.sub( 'colour', 'blue socks and red shoes') 
    'colour socks and colour shoes' 
    >>> p.sub( 'colour', 'blue socks and red shoes', count=1) 
    'colour socks and red shoes'