在句子中查找模式

时间:2014-05-13 11:58:54

标签: python regex

我试图使用Python提供的re模块,但我认为我错过了一些东西。我想要做的是能够说出一个给定的模式是否在句子中,例如:

我的判决"今天的天空是蓝色的" 我想找出模式blu* tod*是否在句子

我尝试过很多东西,比如:

data = 'The sky is blue today'
pattern = 'blu*\stod*
re.match(pattern,data,re.IGNORECASE) // doesn't worked
pattern = [blu+]\s[tod+] 
re.search(pattern,data) // Match everything in my sentence, even if the pattern isn't inside

有人能帮助我吗?或者也许可以指出一个关于在句子中找到正则表达式的好教程?

谢谢。

2 个答案:

答案 0 :(得分:1)

您误解了*+在正则表达式中的行为。它们不是文件通配符中的通配符:它们分别是前一个字符的“0或更多”或“1或更多”。所以它正在寻找类似“bluuuuuu todddddd”的东西。

另一个问题是,您可以互换使用matchsearch,但实际上match只会匹配字符串的开头。您需要search

所以你的代码应该是:

data = 'The sky is blue today'
pattern = 'blu.+\stod.+'
re.search(pattern,data)

答案 1 :(得分:-1)

你想学习贪婪和懒惰之间的区别,以及如何使用这个点。我喜欢这个网站:

http://www.regular-expressions.info/dot.html

http://www.regular-expressions.info/repeat.html

相关问题