Python re.search

Kri*_*a M 13 python regex

我有一个字符串变量包含

string = "123hello456world789"
Run Code Online (Sandbox Code Playgroud)

字符串不包含空格.我想写一个正则表达式,只打印包含(az)的单词我尝试了一个简单的正则表达式

pat = "([a-z]+){1,}"
match = re.search(r""+pat,word,re.DEBUG)
Run Code Online (Sandbox Code Playgroud)

match对象仅包含单词Hello且单词World不匹配.

什么时候使用re.findall()我可以得到两个HelloWorld.

我的问题是为什么我们不能这样做re.search()

这怎么办re.search()

Inb*_*ose 13

re.search()在字符串中找到一次模式,文档:

扫描字符串,查找正则表达式模式生成匹配项的位置,并返回相应的MatchObject实例.如果字符串中没有位置与模式匹配,则返回None; 请注意,这与在字符串中的某个点找到零长度匹配不同.

为了匹配每一个事件,您需要re.findall(),文档:

返回字符串中pattern的所有非重叠匹配,作为字符串列表.从左到右扫描字符串,并按找到的顺序返回匹配项.如果模式中存在一个或多个组,则返回组列表; 如果模式有多个组,这将是一个元组列表.结果中包含空匹配,除非它们触及另一个匹配的开头.

例:

>>> import re
>>> regex = re.compile(r'([a-z]+)', re.I)
>>> # using search we only get the first item.
>>> regex.search("123hello456world789").groups()
('hello',)
>>> # using findall we get every item.
>>> regex.findall("123hello456world789")
['hello', 'world']
Run Code Online (Sandbox Code Playgroud)

更新:

由于您的重复问题(如此链接所述),我在此处添加了其他答案:

>>> import re
>>> regex = re.compile(r'([a-z][a-z-\']+[a-z])')
>>> regex.findall("HELLO W-O-R-L-D") # this has uppercase
[]  # there are no results here, because the string is uppercase
>>> regex.findall("HELLO W-O-R-L-D".lower()) # lets lowercase
['hello', 'w-o-r-l-d'] # now we have results
>>> regex.findall("123hello456world789")
['hello', 'world']
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您提供的第一个示例失败的原因是因为大写,您可以简单地添加re.IGNORECASE标志,但您提到匹配应该只是小写.