Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Result in Regex

Tags:

python

regex

pattern = r'[ -\\[\\]]'
regex = re.compile(pattern)
name = '123[ shiv'
new_name = regex.sub('_',name)

gives result(new_name) ::

'_____shiv'

instead of::

'123__shiv'

..thanx in advance

like image 536
shivMagus Avatar asked Jan 28 '13 19:01

shivMagus


1 Answers

Your regex is creating a range from whitespace (ASCII Code - 32) to opening bracket - [(ASCII Code - 91) because of that - in between. And that range includes the numbers 0 to 9 (ASCII Code - 48 to 57).

You need to change your regex to: -

pattern = '[- \\[\\]]'

Moved - at the beginning.

like image 151
Rohit Jain Avatar answered Sep 26 '22 15:09

Rohit Jain