在Python中使用正则表达式更新字符串

时间:2019-04-01 23:37:26

标签: python regex

我很确定我的问题很简单,但是我找不到答案。假设我们有一个输入字符串,例如:

(last_updated, id) > (timestamp with time zone '2019-03-28 23:30:22.496+00:00', 0)

现在,我想简单地替换每个单词-一般来说,每个子字符串 使用正则表达式 ,这里的“单词”仅是一个示例-输入另一个字符串 ,其中也包括原始字符串 。例如,我想在输入中每个单词的左侧和右侧添加一个input = "This is an example"。并且,输出将是:

@

解决方案是什么?我知道如何使用output = "@This@ @is@ @an@ @example@" re.sub,但是我不知道如何使用它们来更新原始匹配的字符串而不用其他东西完全替换它们。

4 个答案:

答案 0 :(得分:1)

您可以为此使用捕获组。

import re

input = "This is an example"
output = re.sub("(\w+)", "@\\1@", input)

捕获组是您以后可以引用的内容,例如在替换字符串中。在这种情况下,我要匹配一个单词,将其放入捕获组,然后用相同的单词替换它,但是添加@作为前缀和后缀。

您可以在docs中详细了解python中的正则表达式。

答案 1 :(得分:1)

以下是将W与环视一起使用的选项:

re.sub

答案 2 :(得分:0)

这是没有re库

a = "This is an example"
l=[]
for i in a.split(" "):
    l.append('@'+i+'@')

print(" ".join(l))

答案 3 :(得分:0)

您只能将单词边界与\b匹配:

import re

input = "This is an example"
output = re.sub(r'\b', '@', input)
print(output)


@This@ @is@ @an@ @example@