简体   繁体   English

Python - 在字符串变量中查找并替换正则表达式子字符串

[英]Python - Find and replace regex substring in a string variable

I have a variable with a multiline string and I'm trying to replace the line test v1.0 with upside but the problem is I'm trying to replace it only if the entire line matches the pattern so it shouldn't replace the first test v1.0.1 我有一个带有多行字符串的变量,我正在尝试用upside替换行test v1.0 ,但问题是我只是在整个行匹配模式时才尝试替换它,所以它不应该替换第一个test v1.0.1

pkgLogExtract = dedent("""
                      test v1.0.1
                      nothing

                      test v1.0
                      out
                      in
                      flip
                      """)

print (re.sub(r'\^test v1.0\$', "upside", pkgLogExtract, 1))

I tried using re.sub and putting '\\^test v1.0\\$' as the pattern to replace but it doesn't replace anything. 我尝试使用re.sub并将'\\^test v1.0\\$'作为要替换的模式,但它不会替换任何内容。 I've also tried it with the raw flag, so r'\\^test v1.0\\$' but that doesn't replace anything either. 我也尝试过使用raw标志,所以r'\\^test v1.0\\$'但是它也没有替换任何东西。 Any idea what I could do? 知道我能做什么吗?

\\^ matches a literal ^ . \\^匹配文字^ Same goes about $ . 同样的是$ You need to pass flags=re.M to the re.sub and remove the backslashes from ^ and $ so that they could match the start and end of line respectively. 您需要将flags=re.M传递给re.sub并从^$删除反斜杠,以便它们可以分别匹配行的开头和结尾。 And escape the . 逃避了. .

See this IDEONE demo : 看到这个IDEONE演示

import re
pkgLogExtract = """
test v1.0.1
nothing
test v1.0
out
in
flip
"""

print (re.sub(r'^test v1\.0$', "ngn", pkgLogExtract, 1, flags=re.M))

Note: I think you know that 1 stands for a single replacement (only the first match will get replaced). 注意:我想你知道1代表一个替换(只有第一个匹配将被替换)。

Note 2: you may omit flags= and use re.M , but a lot of people forget to use the above mentioned count argument, so it is best to keep the argument name here. 注2:你可以省略flags=并使用re.M ,但是很多人忘记使用上面提到的count参数,所以最好在这里保留参数名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM