Some Characters That Need To Use '\' Before Them To Delete
Solution 1:
Special characters (.
, ?
, (
, )
, ...) should be escaped to match literally:
You can find special characters from here - Regular Expression Syntax.
But you don't need to do it yourself. You can use re.escape
:
>>>import re>>>re.escape('(')
'\\('
>>>print(re.escape('('))
\(
Solution 2:
Since from your question it appears that you just want to delete certain characters from a string, you don't even need to use regex at all. The easiest way to do this in python is using the replace
method of string objects:
>>>my_source = 'Hello, world!'>>>my_source.replace(", world", "")
'Hello!'
If you have a list of strings to delete from your input, you can do it like this:
>>>my_source = 'ABCDEFG_HI(JKLM).NOP'>>>deletions = ('_', '(', ')', 'EF', 'O')>>>for deletion in deletions:... my_source = my_source.replace(deletion, "")...>>>my_source
'ABCDGHIJKLM.NP'
Solution 3:
Which characters need '\' before them to delete from a text ?
Characters you must and must not escape depends on the regular expression indication you're working with.
For the most part the following are characters that need escaped outside of character classes []
are:
.^$*+?()[{\|
And the characters ^-]\
need escaped inside character classes. It's not always needed to escape -
inside character classes, but to me this is alot safer to do.
But note as I stated this does depend on the regex indication you are working with.
Examples using re.sub()
Replace the, (
and )
in the string..
oldStr = '(foo) bar (baz)'print re.sub(r'[()]+', '', oldStr)
Output:
foo bar baz
Example using re.search()
We are using re.search
to find the text between the first (
and )
in the string. We escape the (
next use a regex capture group ([a-zA-Z]+)
looking for word characters, ending it with )
m = re.search('\(([a-zA-Z]+)\)', oldStr)
print m.group(1) #prints 'foo'
Example using re.findall()
m = re.findall(r'\(([a-zA-Z]+)\)', oldStr)
print", " . join(m)
# prints `foo, baz`
Post a Comment for "Some Characters That Need To Use '\' Before Them To Delete"