Kyle Grage
Kyle Grage

Reputation: 765

Simple Python Regex not matching

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?

Upvotes: 0

Views: 64

Answers (2)

Andre Scholich
Andre Scholich

Reputation: 131

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

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

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

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

Upvotes: 3

Related Questions