Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String replace based on chars NOT in RegEx

Tags:

Is it possible to create a reqex that finds characters that are NOT is a specific set?

Rather than Blacklisting a bunch of characters and replacing them, it would be easier for me to allow a certain set and replace characters that are not in that set.

My set looks like this: [.a-zA-Z0-9]

I would like to do something like this:

clean_filename = re.sub(r'([.a-zA-Z0-9])', "_", filename)

obviously this code would replace the characters I want to keep, is there a way to replace the characters NOT in that set?

like image 570
MattoTodd Avatar asked Mar 03 '11 16:03

MattoTodd


2 Answers

Yes, use the ^ negation "modifier": r'[^.a-zA-Z0-9]'

like image 84
ThiefMaster Avatar answered Sep 28 '22 07:09

ThiefMaster


clean_filename = re.sub(r'[^.a-zA-Z0-9]', "_", filename)
like image 27
Petri Lehtinen Avatar answered Sep 28 '22 07:09

Petri Lehtinen