Ami*_*mir 0 regex string python-2.7
我有一个字符串如下:
str = 'chem biochem chem chemi hem achem abcchemde chem\n asd chem\n'
Run Code Online (Sandbox Code Playgroud)
我想用"化学"代替"chem"这个词,同时保留行尾字符('\n').我也希望正则表达式不匹配'biochem','chemi','hem','achem'和'abcchemde'等词.我怎样才能做到这一点?
这是我正在使用但它不起作用:
import re
re.sub(r'[ ^c|c]hem[$ ]', r' chemistry ', str)
Run Code Online (Sandbox Code Playgroud)
谢谢
使用单词边界:
>>> s = 'chem biochem chem chemi hem achem abcchemde chem\n asd chem\n'
>>> import re
>>> re.sub(r'\bchem\b','chemistry',s)
'chemistry biochem chemistry chemi hem achem abcchemde chemistry\n asd chemistry\n'
Run Code Online (Sandbox Code Playgroud)
只是一个注释,不要str用作变量名,它涵盖了内置str类型