我有以下文字:
最佳内容营销技巧,使您的网站脱颖而出
我需要用正则表达式找出"最佳"和"休息"之间的文本是否包含"营销"一词:
我的公式如下:(?<=Best|)(marketing?)(?=Rest)
。
仅当我想在"Rest"之前找到一个单词(在本例中为"the "(时,此公式才有效。
如何搜索两个指定字符串之间的任何单词是否与我的关键字匹配?
也许是这样的:
b[Bb]estb.*b[Mm]arketingb.*b[Rr]estb
或者代替字符类,首先设置不区分大小写的标志:
(?i)bbestb.*bmarketingb.*brestb
我使用单词边界只是为了防止最佳和休息或营销成为子字符串。
对字符串中的正则表达式模式执行不区分大小写的搜索, 模式具有"最佳"一词,然后是任意数量的任意字符, 然后是一个指定的关键字(例如"marketing"(,然后是任意数量的任意字符,最后是单词"Rest":
import re
text = "Best Content Marketing Tips to Make Your Website Standout from the Rest"
Keyword = "marketing" # Customize your search-word here
pattern = re.compile(r"Best.*({}).*Rest".format(Keyword), re.I)
print("Found match in text: n", pattern.search(text))
# See if your keyword was matched inside the searched text:
print("nFound following keyword in text:n", pattern.search(text).group(1))
输出:
Found match in text:
<re.Match object; span=(0, 71), match='Best Content Marketing Tips to Make Your Website >
Found following keyword in text:
Marketing