Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I need an extra space in the regex pattern to make it work properly?

Tags:

python

regex

When I write following code:

m = re.findall('\sf.*?\s','a f fast and friendly dog');

I get output: [' f ', ' friendly ']

But when I provide extra space between f & fast, I get following output which I expected from the previous one. Code is as follows

m = re.findall('\sf.*?\s','a f  fast and friendly dog');

Output:

[' f ', ' fast ', ' friendly ']

Can anyone tell me why I am not getting later output in first case (without inserting extra space between f & fast)?

like image 881
Mr. Sigma. Avatar asked Jan 29 '23 15:01

Mr. Sigma.


1 Answers

Because your pattern ends in \s. Regex matches are non-overlapping, so the first match ' f ' matches the trailing space, making the rest of the string begin with 'fast' instead of ' fast'. 'fast' does not match a pattern starting with \s

like image 102
Adam Smith Avatar answered Feb 02 '23 11:02

Adam Smith