Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex removing non alpha numeric characters from string except brackets

Tags:

python

regex

I have the following regex , which remove all no alpha numeric characters from a string text

re.sub(r'[^a-zA-Z0-9]',' ', text)

How can I modify this expression to include the characters '[' and ']' in the string text ?

like image 683
Tomarinator Avatar asked Jul 24 '26 19:07

Tomarinator


1 Answers

Add [, ] to the charcter class ([ .. ]) with escaping.

re.sub(r'[^a-zA-Z0-9\[\]]',' ', text)

Example:

>>> re.sub(r'[^a-zA-Z0-9\[\]]', ' ', 'a,b[c-d]!')
'a b[c d] '
like image 198
falsetru Avatar answered Jul 27 '26 10:07

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!