kollo
kollo

Reputation: 1311

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

Upvotes: 1

Views: 3951

Answers (1)

Jerry
Jerry

Reputation: 71538

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

Upvotes: 6

Related Questions