0

So I was trying to answer a question on SO when I ran into this issue. Basically a user had the following string:

Adobe.Flash.Player.14.00.125.ie

and wanted to replace it with

Adobe Flash Player 14.00.125 ie

so I used the following re.sub call to solve this issue:

re.sub("([a-zA-Z])\.([a-zA-Z0-9])",r"\1 \2",str)

I then realized that doesn't remove the dot between 125 and ie so I figured I'd try to match another pattern namely:

re.sub("([a-zA-Z])\.([a-zA-Z0-9])|([0-9])\.([a-zA-Z])",r"\1\3 \2\4",str)

When I try to run this, I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/re.py", line 151, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/usr/lib64/python2.6/re.py", line 278, in filter
    return sre_parse.expand_template(template, match)
  File "/usr/lib64/python2.6/sre_parse.py", line 793, in expand_template
    raise error, "unmatched group"
sre_constants.error: unmatched group

Now, I understand that it's complaining because I'm trying to replace the match with an unmatched group but is there a way around this without having to call re.sub twice?

1 Answer 1

1

Without any capturing groups,

>>> import re
>>> s = "Adobe.Flash.Player.14.00.125.ie"
>>> m = re.sub(r'\.(?=[A-Za-z])|(?<!\d)\.', r' ', s)
>>> m
'Adobe Flash Player 14.00.125 ie'
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, another answer on that question used this method. I was interested in seeing how you can reference captured groups if they don't match. +1 for an alternative.
if we use the logical OR operator in regex while back-referencing, then it's impossible to refer the grouped characters through back reference.
Aha. Thanks @Avinash Raj
The main thing in regex is, we need to solve the problem without any capturing groups(ie; through matching only). If it's not possible through matching then only we go for grouping.

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.