栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用动态正则表达式匹配字符串中的整个单词

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用动态正则表达式匹配字符串中的整个单词

为什么不使用 单词边界

match_string = r'b' + word + r'b'match_string = r'b{}b'.format(word)match_string = rf'b{word}b'          # Python 3.7+ required

如果您有一个单词列表(例如,在

words
变量中)要与整个单词匹配,请使用

match_string = r'b(?:{})b'.format('|'.join(words))match_string = rf'b(?:{"|".join(words)})b'         # Python 3.7+ required

在这种情况下,您将确保仅当单词被非单词字符包围时才被捕获。另请注意,

b
字符串开头和结尾处的匹配项。因此,添加3个替代方案毫无用处。

样例代码:

import restrn = "word hereword word, there word"search = "word"print re.findall(r"b" + search + r"b", strn)

我们找到了3个匹配项:

['word', 'word', 'word']

关于“单词”边界的注释

当“单词”实际上是任何字符的大块时,

re.escape
在传递到正则表达式模式之前,应先将它们打包:

match_string = r'b{}b'.format(re.escape(word)) # a single escaped "word" string passedmatch_string = r'b(?:{})b'.format("|".join(map(re.escape, words))) # words list is escapedmatch_string = rf'b(?:{"|".join(map(re.escape, words))})b' # Same as above for Python 3.7+

如果要匹配的单词整个单词可能以特殊字符开头/结尾,

b

将不起作用,请使用 明确的单词边界

match_string = r'(?<!w){}(?!w)'.format(word)match_string = r'(?<!w)(?:{})(?!w)'.format("|".join(map(re.escape, words)))

如果单词边界是空格字符或字符串的开始/结尾,请使用 空格边界

(?<!S)...(?!S)

match_string = r'(?<!S){}(?!S)'.format(word)match_string = r'(?<!S)(?:{})(?!S)'.format("|".join(map(re.escape, words)))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653179.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号