Loading...
Loading...
Test Python regular expressions with live preview and explanations
import re
pattern = r"\d+"
text = "There are 42 apples and 7 oranges in 3 baskets."
result = re.findall(pattern, text)
print(result)re.match() only checks for a match at the beginning of the string, while re.search() scans the entire string looking for the first location where the pattern produces a match. Use re.search() when you want to find a pattern anywhere in the string.
Use re.findall() to get a list of all non-overlapping matches. For match objects with position info, use re.finditer() which returns an iterator of match objects.
The r prefix creates a raw string literal, which tells Python not to interpret backslashes as escape sequences. This is important for regex because patterns use backslashes frequently (like \d, \w, \s). Without the r prefix, you would need to double every backslash.
Pass the re.IGNORECASE flag (or re.I) as the flags argument: re.findall(pattern, text, flags=re.IGNORECASE). You can also use the inline flag (?i) at the start of your pattern.
A capturing group is created with parentheses (). It captures the matched text so you can extract it later. When using re.findall() with groups, it returns the group contents instead of the full match. Use (?:...) for non-capturing groups when you need grouping without capturing.
re.findall() - Find ALL matches, return listre.search() - Find FIRST match anywherere.match() - Match at START of string onlyre.sub() - Replace all matches