5

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?
2
  • In that particular case, you could have use : re.split('X', str). Commented Mar 4, 2011 at 9:49
  • @dugres: not really, if the string looked like XaXbXcXddXeeeX, the pattern would fail by returning dd and eee (and some empty string at the beginning and end). Commented Mar 4, 2011 at 16:22

2 Answers 2

7

You can use a lookbehind assertion:

pattern = r'(?<=X)([a-z])X'
Sign up to request clarification or add additional context in comments.

2 Comments

I believe (but could be convinced otherwise) that lookbehind is a Python 2.7 feature -- which is not to criticize this solution; if you're going to go with RegExes, it's the only way.
That is incorrect, lookbehind assertions have been available since Python 2.0. docs.python.org/release/2.0/lib/re-syntax.html
0

I do not know python, however this regex works i tested in gskinner too ([^(?:X)+])+.

Hope this helps you

3 Comments

the following pattern also works.. ([^X])+ give this a try too and let me know if it helps. The full regex is : /([^(?:X)+])+/gi
Your patterns matches all characters that "are not uppercase X", which is quite different from "all lowercase characters surrounded by an X on either side". e.g. if the string passed looks like this XaXbbXcXdXeXfXggX, it would fail, as it would also match characters b and g, even though they don't have X on both sides.
as i select all the characters other than X, i thought that you could useup all the matches. anyways b,g are all surrounded by X. thanks for your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.