Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: how to match overlapping patterns (maybe Python specific)

Tags:

python

regex

I have a string that looks like this: "XaXbXcX". I'm looking to match any lowercase letters surrounded by X on either side. I tried this in Python, but I'm not getting what I'm looking for:

import re
str = "XaXbXcX"
pattern = r'X([a-z])X'
matches = re.findall(pattern, str) # gives me ['a', 'c']. What about b?
like image 752
Michael Ekoka Avatar asked Mar 04 '11 03:03

Michael Ekoka


1 Answers

You can use a lookbehind assertion:

pattern = r'(?<=X)([a-z])X'
like image 83
Jochen Ritzel Avatar answered Sep 26 '22 19:09

Jochen Ritzel