在字符串的开始、中间和结尾匹配完整的单词

时间:2022-12-04 20:11:04

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.b c odef这样替换文本:

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()中完成吗?

1 个解决方案

#1


3  

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).

注意,原始regex字符串更安全,可以转义。字符(几乎匹配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)

ideone demo

ideone演示

(?<!\S) will prevent a match if abc.def is preceded by a non-space character.

(?

(?!\S) will prevent a match if abc.def is followed by a non-space character.

如果abc.def后面跟着一个非空格字符,则会阻止匹配。

#1


3  

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).

注意,原始regex字符串更安全,可以转义。字符(几乎匹配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)

ideone demo

ideone演示

(?<!\S) will prevent a match if abc.def is preceded by a non-space character.

(?

(?!\S) will prevent a match if abc.def is followed by a non-space character.

如果abc.def后面跟着一个非空格字符,则会阻止匹配。