我有regex https://regex101.com/r/2H5ew6/1
(!|@)(1)
Hello!1 World
和我想要得到第一个标记(!|@),并将数字1
更改为另一个数字2
我做了
{1}2_
1\2_
但是它会添加额外的文本我只想改变数字
我期望结果是
Hello!2_World
和使用@为
Hello@2_World
匹配并捕获命名捕获组(这里称为char
)中的!
或@
,如果后面跟着一个或多个数字和一个空格:
(?P<char>[!@])d+s
替换命名的捕获,g<char>
后面跟着2_
:
g<char>2_
演示如果您只希望在!
或@
后面有1
时进行替换,则将d+
替换为1
。
在您的替换中您需要将{1}2_
更改为2_
。
string = "Hello!1 World"
pattern = "(!|@)(1)"
replacement = "2_"
result = re.sub(pattern, replacement, string)
为什么不:string.replace('!1 ', '!2_').replace('@1 ', '@2_')
?
>>> string = "Hello!1 World"
>>> repl = lambda s: s.replace('!1 ', '!2_').replace('@1 ', '@2_')
>>> string2 = repl(string)
>>> string2
'Hello!2_World'
>>> string = "Hello!12 World"
>>> string2 = repl(string)
>>> string2
'Hello!12 World'
您的模式应该替换为g<1>2_
Regex演示
您还可以将模式缩短为使用字符类[!@]
和匹配的单个捕获,并使用与上述相同的替换。
([!@])1
Regex演示
或者使用没有任何组的lookbehind断言并替换为2_
(?<=[!@])1
Regex演示