使用python和regex在字符串中查找关键字

时间:2014-03-09 09:43:28

标签: python regex string

我想在字符串中找到一个关键字,可以在字符串的开头,结尾或任何位置。

我从那样开始:

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 个答案:

答案 0 :(得分:4)

只需使用字边界:

regex = r'\bin ocean\b'

单词边界在\w个字符与\W字符之间,或\w^$之间匹配。

regex101 demo