Chris Bunch Chris Bunch - 2 months ago 8
Python Question

Python - Use a Regex to Filter Data

Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use

gsub
:

>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"


What would the equivalent function be in Python?

Answer
import re
re.sub(pattern, '', s)

Docs

Comments