Using ascii numbers in regular expression

MRAB google at mrabarnett.plus.com
Thu Apr 30 16:13:02 CEST 2009


Lie Ryan wrote:
> MRAB wrote:
>> You're almost there:
>>
>>     re.subn('\x61','b','aaaa')
>>
>> or better yet:
>>
>>     re.subn(r'\x61','b','aaaa')
> 
> Wouldn't that becomes a literal \x61 instead of "a" as it is inside raw 
> string?
> 
Yes. The re module will understand the \x sequence within a regular
expression.

The reason I say that the second solution is better is because you say:

"How can I use the ascii number of a character in a regular expression
(module re) instead of the character itself?"

Certain characters have a special meaning in regular expressions, eg
'*', so if you tried to search for '*' (or '\x2A') you would get an
exception. The solution would be to search for r'\*' or r'\x2A'.



More information about the Python-list mailing list