Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex positive look ahead

Tags:

python

regex

I have the following regex that is supposed to find sequence of words that are ended with a punctuation. The look ahead function assures that after the match there is a space and a capital letter or digit.

pat1 = re.compile(r"\w.+?[?.!](?=\s[A-Z\d])"

What is the function of the following lookahead?

pat2 = re.compile(r"\w.+?[?.!](?=\s+[A-Z\d])"

Is Python 3.2 supporting variable lookahead (\s+)? I do not get any error. Furthermore I cannot see any differences in both patterns. Both seem to work the same regardless the number of blanks that I have. Is there an explanation for the purpose of the \s+ in the look ahead?

like image 846
andreSmol Avatar asked Aug 14 '26 17:08

andreSmol


1 Answers

I'm not really sure what you are tying to achieve here.

Sequence of words ended by a punctuation can be matched with something like:

re.findall(r'([\w\s]*[\?\!\.;])', s)

the lookahead requires another string to follow?

In any case:

  • \s requires one and only one space;
  • \s+ requires at least one space.

And yes, the lookahead accepts the "+" modifier even in python 2.x

The same as before but with a lookahead:

re.findall(r'([\w\s]*[\?\!\.;])(?=\s\w)', s)

or

re.findall(r'([\w\s]*[\?\!\.;])(?=\s+\w)', s)

you can try them all on something like:

s='Stefano ciao.   a domani. a presto;'

Depending on your strings, the lookahead might be necessary or not, and might or might not change to have "+" more than one space option.

like image 168
Stefano Avatar answered Aug 17 '26 07:08

Stefano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!