簡體   English   中英

使用python和regex在字符串中查找關鍵字

[英]find a keyword in a string with python and regex

我想在字符串的開頭,結尾或字符串中的任何地方找到關鍵字。

我從這樣的事情開始:

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

只需使用單詞邊界:

regex = r'\bin ocean\b'

單詞邊界在\\w字符和\\W字符之間,或\\w^$之間匹配。

regex101演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM