This question already has an answer here:
这个问题在这里已有答案:
- Python regular expression match whole word 3 answers
- Python正则表达式匹配整个单词3答案
Example string: "office administration in delhi"
示例字符串:“德里办公室管理”
I want to replace in from the string with a blank. But when I do, s.replace('in',"")
, the in of administration also becomes blank.
我想用空格替换字符串。但当我这样做时,s.replace('in',“”),管理中的内容也变成了空白。
This is just a sample. The string and the word to replace may vary.
这只是一个例子。字符串和要替换的单词可能会有所不同。
Is there some way to replace only the exact match?
有没有办法只替换完全匹配?
1 个解决方案
#1
10
You can use regular expression \bin\b
. \b
here means word boundary. \bin\b
will match in
surrounded by word boundary (space, punctuation, ...), not in
in other words.
您可以使用正则表达式\ bin \ b。 \ b这里的意思是单词边界。 \ bin \ b将匹配字边界(空格,标点符号......),换句话说,不是。
>>> import re
>>> re.sub(r'\bin\b', '', 'office administration in delhi')
'office administration delhi'
See re.sub
.
见re.sub。
#1
10
You can use regular expression \bin\b
. \b
here means word boundary. \bin\b
will match in
surrounded by word boundary (space, punctuation, ...), not in
in other words.
您可以使用正则表达式\ bin \ b。 \ b这里的意思是单词边界。 \ bin \ b将匹配字边界(空格,标点符号......),换句话说,不是。
>>> import re
>>> re.sub(r'\bin\b', '', 'office administration in delhi')
'office administration delhi'
See re.sub
.
见re.sub。