23

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?

3 Answers 3

37

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

Sign up to request clarification or add additional context in comments.

1 Comment

The user could enter ".." as a file name. Would that be ok?
6
clean_filename = re.sub(r'[^.a-zA-Z0-9]', "_", filename)

Comments

5

Try with:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.