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 theremodule 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 YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to match any symbol except a given one with Python regex?
- How to use word boundaries in Python Regex?
- How to match one or more occurence in Python regex?
- How to match a URL using Python regex?
- How to get the href attribute value from a regex in Python?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
- How to remove numbers from a string using Python regex?
See more codes...