簡體   English   中英

匹配句子中以模式結尾的單詞

[英]Match a word ending with pattern in a sentence

如何使用正則表達式在以模式結尾的句子中查找單詞(S)

我有我想在句子中匹配的模式列表 例如 my_list = ['one', 'this']

句子 = '某人這樣做某人這是'

結果應僅返回以 my_list 中的項目結尾的單詞

['Someone','dothis'] 僅

因為我不想匹配 onesome 或 thisis

您可以使用以下模式:

\b(\w+(one|this))\b

它表示匹配單詞邊界內的整個單詞( \\b...\\b ),並且在整個單詞中匹配任何單詞字符( \\w+ ),后跟文字onethis(one|this)

https://regex101.com/r/UzhnSw/1/

您可以使用單詞邊界元字符\\b結束您的模式。 它將匹配任何不是單詞字符的內容,包括字符串的結尾。 因此,在這種特定情況下,模式將是(one|this)\\b

要從my_list變量實際創建正則表達式,假設不存在保留字符,您可以執行以下操作:

import re

def words_end_with(sentence, my_list):
    return re.findall(r"({})\b".format("|".join(my_list)), sentence)

如果您使用的是 Python 3.6+,您還可以使用f-string來在字符串本身內部進行格式化:

import re

def words_end_with(sentence, my_list):
    return re.findall(fr"({'|'.join(my_list)})\b", sentence)

https://www.regular-expressions.info/wordboundaries.html

暫無
暫無

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

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