我有一个字符串如下:
str = 'chem biochem chem chemi hem achem abcchemde chem\n asd chem\n'我想用“化学”一词代替“化学”,同时保留行字符('\n')的末尾。我也想要的regex不匹配的词,如‘生物化学’,'chemi',‘哼哼’,'achem‘和’and化学‘。我该怎么做?
下面是我正在使用的东西,但它不起作用:
import re
re.sub(r'[ ^c|c]hem[$ ]', r' chemistry ', str)谢谢
发布于 2015-11-24 16:40:13
我刚找到答案。感谢@Jota。
超级简单的Regex如下所示:
re.sub(r'\bchem\b', r' chemistry ', str)发布于 2015-11-24 16:37:37
使用单词边界:
>>> 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'请注意,不要使用str作为变量名,它涵盖了内置str类型
发布于 2015-11-24 16:37:54
您需要使用\b来匹配单词边界:
import re
re.sub(r'\bchem\b', r'chemistry', mystring)(正如R指出的那样,您应该避免使用str作为变量名。)
https://stackoverflow.com/questions/33898997
复制相似问题