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 match a plus sign in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a UUID using Python regex?
- How to remove numbers from a string using Python regex?
- How to match a URL path using Python regex?
- How to validate an IP using Python regex?
- How to replace in a file using Python regex?
- How to replace a certain group using Python regex?
See more codes...