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

标签 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):]

所以如果我做某事喜欢

>>> 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'

关于python - 正则表达式不过是写在匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/140182/

相关文章:

python - Django session 管理

python - 如何用python处理.mdb Access 文件

sql - Oracle - REGEXP_LIKE 未给出所需结果

c# - 正则表达式只修剪句子中的最后一个 ()

python - 正则表达式删除python中的特定单词

python - 闪烁的结束屏幕 - pygame

python - 二维点的最小二乘拟合不通过对称轴

python - 使用 Python Paramiko exec_command 执行时,一些 Unix 命令失败并显示 "<command> not found"

java - 由 : problem 分隔的字节的正则表达式

regex - 如何仅在 powershell 的子字符串中替换特定字符