python-regexHow to match any character with Python regex?
The Python re
module provides a set of functions that allows us to match any character using regular expressions. To match any character, we can use the .
(dot) character. The .
character matches any single character except for a newline.
Example code
import re
pattern = r".*"
string = "Hello World!"
match = re.search(pattern, string)
if match:
print("Match found:", match.group())
else:
print("No match found")
Output example
Match found: Hello World!
Code explanation
import re
: This imports there
module which provides functions for working with regular expressions.pattern = r".*"
: This creates a regular expression pattern that matches any character. The.
character matches any single character except for a newline. The*
character matches the preceding character 0 or more times.string = "Hello World!"
: This creates a string that we will use to search for a match.match = re.search(pattern, string)
: This searches thestring
for a match using thepattern
.if match:
: This checks if a match was found.print("Match found:", match.group())
: This prints the matched string.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a UUID using Python regex?
- How to replace all using Python regex?
- How to use word boundaries in Python Regex?
- How to perform a zero length match with Python Regex?
- How to match whitespace in Python regex?
- How to split using Python regex?
- How to get a group from a regex in Python?
- How to match a URL path using Python regex?
- How to ignore case in Python regex?
See more codes...