正则表达式,但用于在匹配中写入

miy*_*iya 1 python regex

当使用正则表达式时,我们通常会使用它们来提取某种信息.我需要的是用其他值替换匹配值...

现在我正在这样做......

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):]
Run Code Online (Sandbox Code Playgroud)

所以,如果我喜欢

>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
Run Code Online (Sandbox Code Playgroud)

它用'ooo'改变(...).

你们知道用python正则表达式我们能做到吗?

非常感谢!

Swa*_*ati 7

sub (replacement, string[, count = 0])
Run Code Online (Sandbox Code Playgroud)

sub返回通过替换替换替换字符串中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'
Run Code Online (Sandbox Code Playgroud)