1

I have a particular problem with regular expressions. Consider this sentence of valid words:

sphere_a [sS]phere_b [sS]pher* [sS]pher* sph[eE]* sphere_a ^sphe* ^sp[hH]er*

I want these words to be split up, so I can use each one separately for operations downstream. To do this I am currently using 2 regular expressions.

One that matches the word at the start of the sentence:

(?<=^)(?P<pattern>[\w\^\?\*\[\]]+)(?=\s|$)

and one that matches all the others:

(?<=\s)(?P<pattern>[\w\^\?\*\[\]]+)(?=\s|$)

It would be nice to know if this could fit in one expression? It would save the looping.


Strangely enough the obvious first try:

(?<=^|\s)(?P<pattern>[\w\^\?\*\[\]]+)(?=\s|$)

fails with an error:

Invalid regular expression: look-behind requires fixed-width pattern

I am using Pythons re module, and pythex.org for validation.

1 Answer 1

2

You can split your patterns easily with

regexs = 'sphere_a [sS]phere_b [sS]pher* [sS]pher* sph[eE]* sphere_a ^sphe* ^sp[hH]er*'.split(). 

Then you can iterate over the patterns like this:

for regex in regexs:
    m = re.findall(regex, content)

But it will return duplicate matches.

1
  • 1
    I believe your approach of splitting is probably much more practical than doing this by regex! Accepted - Thanks! Feb 2, 2016 at 19:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.