python-regexHow to use backslash in Python regex?
Using backslash in Python regex is a way to escape special characters. For example, if you want to match a literal backslash, you need to use two backslashes in the regex.
import re
pattern = r"\\"
if re.search(pattern, "This is a backslash: \\"):
print("Match!")
else:
print("No match!")
Output example
Match!
Code explanation
import re
: imports there
module which provides regular expression matching operationspattern = r"\\"
: creates a regular expression pattern object with a literal backslashif re.search(pattern, "This is a backslash: \\"):
: searches for the pattern in the given stringprint("Match!")
: prints "Match!" if the pattern is foundprint("No match!")
: prints "No match!" if the pattern is not found
Helpful links
More of Python Regex
- How to replace a certain group using Python regex?
- How to match a UUID using Python regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to perform a zero length match with Python Regex?
- How to replace all using Python regex?
- How to match a hex number with regex in Python?
- How to match a plus sign in Python regex?
- How to match a float with regex in Python?
- How to regex match excluding a character in Python?
See more codes...