简体   繁体   中英

find a keyword in a string with python and regex

I would like to find a keyword in a string that can be at the begining, the end, or anywhere in the string.

I started with something like that:

import re
my_keyword = "in ocean"
regex = r'[^|\,\s]?in ocean\,\s|[^|\,\s]?in ocean$'

should match:

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

should not match:

within ocean, you can find tresure
in oceania there is sirens
tintin ocean, the tresure hunter
do not dive within ocean

Simply use word boundaries:

regex = r'\bin ocean\b'

A word boundary matches between a \\w character and a \\W character, or between a \\w and a ^ or $ .

regex101 demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM