Common Predefined Classes
Lesson 10 of 28 in Coddy's RegEx in Python course.
Predefined character classes simplify the process of writing regular expressions by providing shortcuts for commonly used character classes. Here are some of the most commonly used predefined character classes:
<strong>\d</strong>: Matches any digit (equivalent to[0-9]).<strong>\w</strong>: Matches any word character, which includes letters, digits, and underscores (equivalent to[a-zA-Z0-9_]).<strong>\s</strong>: Matches any whitespace character, including spaces, tabs, and line breaks (equivalent to[ \t\n\r\f\v]).
import re
text = "I have 2 apples and 3 bananas."
pattern = r"\d"
matches = re.findall(pattern, text)
print(matches) # Output: ['2', '3']In the above example, the pattern \d matches any digit in the string text.
Challenge
EasyWrite a function named find_all_digits that takes a text string as input and returns a list of all digits found in the text.
Try it yourself
import re
def find_all_digits(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction3Basic Pattern Syntax
Basic MetacharactersLiteralsCharacter ClassesRangesCommon Predefined ClassesAdvanced Predefined Classes