2
>>> 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?

TheSoldier
  • 484
  • 1
  • 5
  • 25
alwayslz
  • 119
  • 1
  • 8

1 Answers1

7

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']
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Thank you !!! `code`>>> phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-\d\d\d\d') >>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000') [('415', '555'), ('212', '555')] >>> phoneNumRegex = re.compile(r'(?:\d\d\d)-(?:\d\d\d)-\d\d\d\d') >>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000') ['415-555-9999', '212-555-0000'] >>> phoneNumRegex = re.compile(r'(\d\d\d)-(?:\d\d\d)-\d\d\d\d') >>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000') ['415', '212'] `code` – alwayslz Aug 19 '17 at 14:53