python - 正则表达式为什么`findall`什么也找不到,但`search`有效? [英] python - regex why does `findall` find nothing, but `search` works?

查看:219
本文介绍了python - 正则表达式为什么`findall`什么也找不到,但`search`有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>reg = re.compile(r'^\d{1,3}(,\d{3})*$')>>>str = '42'>>>reg.search(str).group()'42'>>>reg.findall(str)['']>>>

蟒蛇正则表达式为什么reg.findall什么都找不到,而reg.search却在上面这段代码中有效?

解决方案

当您在 regex 中有捕获组(用括号括起来)时,findall 将返回匹配被捕获的群体;在您的情况下,捕获的组匹配一个空字符串;如果您想返回整个匹配项,您可以使用 ?: 使其不被捕获;re.search 另一方面忽略捕获组.这些都反映在文档中:

re.findall:

<块引用>

返回字符串中模式的所有非重叠匹配,作为列表字符串.从左到右扫描字符串,并返回匹配项按照找到的顺序.如果模式中存在一个或多个组,返回组列表; 如果模式为元组列表,则这将是元组列表有不止一组.

研究:

<块引用>

扫描字符串寻找第一个位置表达式模式产生一个匹配,并返回一个对应的匹配对象实例.如果字符串中没有位置匹配,则返回 None图案;请注意,这与找到零长度不同匹配字符串中的某个点.

导入重新reg = re.compile(r'^\d{1,3}(?:,\d{3})*$')s = '42'reg.search(s).group()#‘42’reg.findall(s)# ['42']

>>> reg = re.compile(r'^\d{1,3}(,\d{3})*$')
>>> str = '42'
>>> reg.search(str).group()
'42'
>>> reg.findall(str)
['']
>>> 

python regex Why does reg.findall find nothing, but reg.search works in this piece of code above?

解决方案

When you have capture groups (wrapped with parenthesis) in the regex, findall will return the match of the captured group; And in your case the captured group matches an empty string; You can make it non capture with ?: if you want to return the whole match; re.search ignores capture groups on the other hand. These are reflected in the documentation:

re.findall:

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

re.search:

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

import re
reg = re.compile(r'^\d{1,3}(?:,\d{3})*$')
s = '42'
reg.search(s).group()
​# '42'

reg.findall(s)
# ['42']

这篇关于python - 正则表达式为什么`findall`什么也找不到,但`search`有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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