如何匹配python中正则表达式中字符串列表中的任何字符串?

编程入门 行业动态 更新时间:2024-10-26 20:21:52
本文介绍了如何匹配python中正则表达式中字符串列表中的任何字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个字符串列表,

Lets say I have a list of strings,

string_lst = ['fun', 'dum', 'sun', 'gum']

我想创建一个正则表达式,在其中的某个点,我可以匹配我在该列表中的任何字符串,在一个组内,例如:

I want to make a regular expression, where at a point in it, I can match any of the strings i have in that list, within a group, such as this:

import re template = repile(r".*(elem for elem in string_lst).*") template.match("I love to have fun.")

这样做的正确方法是什么?或者是否必须制作多个正则表达式并将它们分别与字符串匹配?

What would be the correct way to do this? Or would one have to make multiple regular expressions and match them all separately to the string?

推荐答案

在管道符|上加入列表,代表正则表达式中的不同选项.

Join the list on the pipe character |, which represents different options in regex.

string_lst = ['fun', 'dum', 'sun', 'gum'] x="I love to have fun." print re.findall(r"(?=("+'|'.join(string_lst)+r"))", x)

输出:['fun']

您不能使用 match,因为它会从一开始就匹配.使用 search 您将只获得第一个匹配项.所以改用 findall.

You cannot use match as it will match from start. Using search you will get only the first match. So use findall instead.

如果您的重叠匹配不是从同一点开始,也可以使用 lookahead.

Also use lookahead if you have overlapping matches not starting at the same point.

更多推荐

如何匹配python中正则表达式中字符串列表中的任何字符串?

本文发布于:2023-11-05 09:05:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   列表中   正则表达式   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!