如何将管道运算符用作正则表达式的一部分? [英] How to use the pipe operator as part of a regular expression?

查看:33
本文介绍了如何将管道运算符用作正则表达式的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配字符串中的网址

I want to match the url within strings like

u1 = "Check this out http://www.cnn.com/stuff lol"
u2 = "see http://www.cnn.com/stuff2"
u3 = "http://www.espn.com/stuff3 is interesting"

像下面这样的工作,但很麻烦,因为我必须重复整个模式

Something like the following works, but it's cumbersome because I have to repeat the whole pattern

re.findall("[^ ]*.cnn.[^ ]*|[^ ]*.espn.[^ ]*", u1)

特别是,在我的真实代码中,我想匹配更多的网站.理想情况下,我可以做类似的事情

Particularly, in my real code I wanted to match a much larger number of web sites. Ideally I can do something similar to

re.findall("[^ ]*.cnn|espn.[^ ]*", u1)

但当然它现在不起作用,因为我没有正确指定网站名称.这如何做得更好?谢谢.

but of course it doesn't work now because I am not specifying the web site name correctly. How can this be done better? Thanks.

推荐答案

非分组匹配.

re.findall("[^ ]*.(?:cnn|espn).[^ ]*", u1)

这篇关于如何将管道运算符用作正则表达式的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆