python-regexHow to match all letters with Python regex?
Python regex can be used to match all letters in a string. The re
module provides a set of functions that allows us to search a string for a match.
import re
# Match all letters
pattern = re.compile(r'[a-zA-Z]')
# Sample string
string = 'Hello World!'
# Find all matches
matches = pattern.findall(string)
# Print matches
print(matches)
Output example
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
The code above uses the re.compile()
function to create a regular expression object. The [a-zA-Z]
part of the expression is used to match all letters in the string. The findall()
method is then used to find all matches in the string. Finally, the print()
function is used to print out the matches.
Parts of the code:
import re
: imports there
module which provides functions for working with regular expressions.pattern = re.compile(r'[a-zA-Z]')
: creates a regular expression object that matches all letters.string = 'Hello World!'
: creates a sample string.matches = pattern.findall(string)
: finds all matches in the string.print(matches)
: prints out the matches.
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...