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

Python正则表达式:单词集的替代

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

Python正则表达式:单词集的替代

正则表达式模块的一个有趣功能是命名列表。有了它,您就不必

|
在非捕获组中包括多个由分隔的选项。您只需要在列表之前定义列表,并通过名称在模式中引用它即可。例:

import regexwords = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]pattern = r'm L<word1> s+ L<word2> s+ L<word3> M'p = regex.compile(pattern, regex.X, word1=words[0], word2=words[1], word3=words[2])s = 'the reasons for'print(p.search(s))

即使此功能不是必需的,它也可以提高可读性。

如果您

|
在之前加入项目,则可以通过re模块实现类似的功能:

import rewords = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]words = ['|'.join(x) for x in words]pattern = r'b ({}) s+ ({}) s+ ({}) b'.format(*words)p = re.compile(pattern, re.X)


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

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

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