python-regexHow to match any letter with Python regex?
To match any letter with Python regex, you can use the \w
character class. This character class will match any alphanumeric character, including both upper and lowercase letters.
Example code
import re
pattern = re.compile(r'\w')
string = 'Hello World!'
matches = pattern.findall(string)
Output example
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
Code explanation
import re
: imports there
module, which contains the functions needed for regular expression matchingpattern = re.compile(r'\w')
: compiles the regular expression pattern\w
, which matches any alphanumeric characterstring = 'Hello World!'
: sets the string to be matchedmatches = pattern.findall(string)
: finds all matches of the pattern in the string
Helpful links
More of Python Regex
- How to match whitespace in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match an IP address with regex in Python?
- How to validate an IP using Python regex?
- How to get all matches from a regex in Python?
- How to match a UUID using Python regex?
- How to match zero or one occurence in Python regex?
See more codes...