Python:re
lastmod 2022-05-25created 2015-03-1019 edits
Compile
Regular expressions can be compiled as below. Once compiled, you do not have to type the regular expression every time.
For reference, case-insensitive matching is done as below.
Repetition metacharacters
| Metacharacter | Meaning |
| | Repeat 0 or more times |
| | Repeat 1 or more times |
| | 0 or 1 time |
| | Repeat m times |
| | Repeat m to n times |
Matching metacharacters
| Metacharacter | Meaning |
| | Matches any character except a newline |
| | Matches the start of the string |
| | Matches the end of the string |
| | One character from a character set |
| | Means "or" |
| | Groups a regular expression |
Escape sequences
| Type | Description |
| | The backslash character itself |
| | Matches any digit |
| | Matches any non-digit character |
| | Matches whitespace characters |
| | Matches anything that is not whitespace |
| | Matches digits or letters |
| | Matches anything that is not a digit or letter |
| | Word boundary. A word is a consecutive string of letters or digits |
| | Not a word boundary |
| | Matches only at the start of the string |
| | Matches only at the end of the string |
Regular expressions for minimal matching
| Symbol | Meaning |
| | Same as |
| | Same as |
| | Same as |
| | Same as |
Flags available in regular expressions
| Flag | Description |
| | Case-insensitive |
| | Makes |
| | |
| | Makes |
| | Makes |
| | Whitespace inside the regular expression is ignored |
Main methods of the re module
| Method | Description |
| | Compiles pattern and returns a regular expression object |
| | Checks whether pattern exists from the start of string and returns a MatchObject instance |
| | Checks whether pattern exists anywhere in string and returns a MatchObject instance |
| | Splits string using pattern as the delimiter and returns a list |
| | Returns the strings in string that satisfy pattern as a list |
| | Returns the strings in string that satisfy pattern as an iterator |
| | Replaces the parts of string that match pattern with repl and returns the resulting string |
| | Same as sub, but returns the result as a tuple (result string, number of matches) |
| | Returns the string with non-alphanumeric characters backslash-escaped. (Useful when using an arbitrary string as a regular expression pattern) |
Match object
A Match object is created as the result of match() or search(), and provides features for processing the search results efficiently.
| Method | Attribute |
| | Returns the subset of the matched string result corresponding to the given index. If the index is '0' or not given, returns the entire matched string. |
| | Returns the matched results as a tuple |
| | Returns named match results as a dictionary |
| | Returns the start index of the matched result string. (If a subset number or given name is passed as an argument, returns the corresponding start index) |
| | Returns the end index of the matched result string. (If a subset number or given name is passed as an argument, returns the corresponding end index) |
| | The position in the original string where the search starts. |
| | The position in the original string where the search ends. |
| | Returns the last index number in the matched result set. (Returns None if there is no match) |
| | Returns the name of the last match in the matched result set. (Returns None if the regular expression's match condition has no name or there is no match) |
| | The original string that is the target of matching. |
match vs search
-
re.match(): searches from the start of the target string and returns the result. -
re.search(): searches the entire target string and returns the result. -
re.findall(): returns all strings (substrings) that match the regular expression as a list. -
re.finditer(): returns all strings (substrings) that match the regular expression as an iterator object.
Match object
The Match object returned as the result of match, search, etc. holds the following information.
-
group(): returns the matched string. -
start(): returns the start position of the matched string. -
end(): returns the end position of the matched string. -
span(): returns a tuple of the (start, end) of the matched string.
Example
Properties dictionary
Assume there are properties in the following format.
They can be read as below.
import re
def readProperties():
with open(PROPERTIES_NAME, 'rb') as f:
result = {}
for line in f:
name = str(re.match(r'^.*=', line).group()).strip()
value = str(line[len(name):]).strip()
name = str(name[:-1]).strip()
result[name] = value
return result
Substitution
You can substitute by group number with arguments like \1.
See also
- Python
- Python:re - regular expressions.
- Python:fnmatch - Unix filename pattern matching.
Favorite site
- 7.2. re — Regular expression operations
- Python HOWTOs: Regular Expression HOWTO
- Python – Regular Expression module 1
- [Recommended] Jump to Python - Regular Expressions
- ┗System∑Sec†ion┛ :: Python – Regular Expression module
References
-
System_Section-Python-Regular_Expression_module.pdf ↩