用Python和正则表达式在字符串中查找关键词
我想在一个字符串中找到一个关键词,这个关键词可以出现在字符串的开头、结尾或者任何地方。
我开始用这样的方式:
import re
my_keyword = "in ocean"
regex = r'[^|\,\s]?in ocean\,\s|[^|\,\s]?in ocean$'
应该匹配:
in ocean there is big fish
in ocean
there is big fish in ocean
there is big fish in ocean but not in lakes
i like to swim in lake, in ocean too
in ocean, there is big fish
不应该匹配:
within ocean, you can find tresure
in oceania there is sirens
tintin ocean, the tresure hunter
do not dive within ocean
1 个回答
6
简单来说,使用单词边界:
regex = r'\bin ocean\b'
单词边界是指在一个 \w
字符和一个 \W
字符之间,或者在一个 \w
字符和 ^
或 $
之间的匹配。