0

Example-1

import re
data = 'astlewoieroiweru@89in.if hd'
stufff = re.findall('@([0-9]*?)', data)
print(stufff)

it prints [''] but why but there is number after the @ symbol , I know it follows non-greedy it is supposed to print ['8'] but it doesn't why? I need someone to explain me this code.

Example-2

import re
data = 'astlewoieroiweru@89in.if hd'
stufff = re.findall('@([0-9]*)', data)
print(stufff)

I know it follows greedy so it took the number after @ and stops when it sees the i, so the output is ['89']. Please explain the example-1, thank you!

InSync
  • 4,851
  • 4
  • 8
  • 30
Astle
  • 9
  • 3
  • 1
    Try regex101.com, it has an interactive tool that lets you enter a regex and a test string, and it explains why the pattern did (or didn't) match – John Gordon May 06 '23 at 02:46
  • 1
    Welcome to Stack Overflow. "I know it follows non-greedy it is supposed to print ['8'] but it doesn't why?" it prints `['']` because it is non-greedy. Try to follow the logic carefully. Why should it match the `8`? If it is non-greedy, then it should match as few things as possible, right? *And it is allowed to match zero things, right?* (Because it says `*`, and not `+`?) So, zero things is a valid match, and that's the best it can do, so that's what it does. – Karl Knechtel May 06 '23 at 03:34
  • @InSync if it is not a typo (i.e., failure to think clearly), then I think it is rather a question about the difference between `*?` and `+?` - which is really just a question about the difference between `*` and `+`. – Karl Knechtel May 06 '23 at 03:38
  • Agree. In that case, the duplicate target would be [this one](https://stackoverflow.com/q/8575281). – InSync May 06 '23 at 03:47
  • https://regex101.com/r/LKu0aC/1 clearly shows `([0-9]*?)` matching an empty string (see the contents of group 1). – Nick May 06 '23 at 06:22

0 Answers0