[Solved] some characters that need to use ‘\’ before them to delete [closed]


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`

solved some characters that need to use ‘\’ before them to delete [closed]