[英]Match complete word at start, middle and end of string
How to replace the complete word abc.def
at start, middle and end of string but do not replace the text like abc.def.au
or d.abc.def
: 如何在字符串的开头,中间和结尾替换完整的单词
abc.def
,但不替换abc.def.au
或d.abc.def
类的文本:
line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub("abc.def", "-----", line)
print(line)
print(new_line)
Current output: 电流输出:
abc.def abc.def.au abc.def d.abc.def abc.def
----- -----.au ----- d.----- -----
Expected output: 预期产量:
abc.def abc.def.au abc.def d.abc.def abc.def
----- abc.def.au ----- d.abc.def -----
Can this be done in one re.sub()
? 可以在一个
re.sub()
吗?
You can use line anchors. 您可以使用线锚。
^
and $
matches only a the start of the string and end of the string respectively, so you could use them like such: ^
和$
仅匹配字符串的开头和字符串的结尾,因此您可以像这样使用它们:
line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub(r"^abc\.def|abc\.def$", "-----", line)
print(line)
print(new_line)
Note that it is safer to raw regex strings, and escape the .
请注意,使用原始正则表达式字符串更安全,并转义
.
character (which matches almost any character in regex). 字符(几乎匹配正则表达式中的任何字符)。
If you want to replace only whole words you will need some lookarounds instead: 如果您只想替换整个单词,则需要一些环视方法:
line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub(r"(?<!\S)abc\.def(?!\S)", "-----", line)
print(line)
print(new_line)
(?<!\\S)
will prevent a match if abc.def
is preceded by a non-space character. 如果
abc.def
前面带有非空格字符,则(?<!\\S)
将阻止匹配。
(?!\\S)
will prevent a match if abc.def
is followed by a non-space character. (?!\\S)
将阻止匹配,如果abc.def
后跟非空格字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.