re.finditer with lookahead and lookbehind

MRAB python at mrabarnett.plus.com
Wed Jun 20 17:06:11 CEST 2012


On 20/06/2012 14:30, Christian wrote:
> Hi,
>
> i have some trouble to split a pattern like s.   Even have this
> problems with the first and last match. Some greedy problems?
>
> Thanks in advance
> Christian
>
> import re
>
> s='v1=pattern1&v2=pattern2&v3=pattern3&v4=pattern4&v5=pattern5&x1=patternx'
> pattern =r'(?=[a-z0-9]+=)(.*?)(?<=&)'
> regex = re.compile(pattern,re.IGNORECASE)
> for match in regex.finditer(s):
> 	print  match.group(1)
>
> My intention:
> pattern1
> pattern2
> pattern3
> pattern4
> pattern5
> patternx
>
You could do it like this:

import re

s = 
'v1=pattern1&v2=pattern2&v3=pattern3&v4=pattern4&v5=pattern5&x1=patternx'
pattern = r'=([^&]*)'
regex = re.compile(pattern, re.IGNORECASE)
for match in regex.finditer(s):
	print match.group(1)

or avoid regex entirely:

 >>> values = [p.partition("=")[2] for p in s.split("&")]
 >>> values
['pattern1', 'pattern2', 'pattern3', 'pattern4', 'pattern5', 'patternx']



More information about the Python-list mailing list