0

Very simply, I am trying to replace a string that contains the substring XX.

import re

def replace_bogus(original, replacement):
    bogus = re.compile('[.]*[X][X][.]*')
    if bogus.match(original) != None:
        original = replacement

    return original

if __name__ == "__main__":
    teststr = replace_bogus('ABXX0123', '')
    print teststr

This code prints out ABXX0123. Why is this regex wrong and what should I use instead?

1
  • 1
    re module have it's own sub method for replacing. Commented Jun 19, 2014 at 15:38

2 Answers 2

3

Because the dot (.) has no special meaning when it's inside a character class (i.e. [.]). The regex doesn't match the text and it returns None.

As has been said in the comments, the re module has its own method for replacing, i.e. the sub method. You can simply use it like so:

import re
p = re.compile(r'XX')
result = re.sub(p, '', 'ABXX0123')
print result // => AB0123
Sign up to request clarification or add additional context in comments.

1 Comment

Adding to that, I've put dots in characters classes because it can be clearer than backslash hell, but doing it for X doesn't make any sense.
0

As you did not state that you want to use regexp. What about:

teststr = 'ABXX0123'
print teststr.replace('XX', '')

Comments

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.