Regular Expressions
在正则表达式中的字符:
- Non-special chars match themselves. 非特殊字符,匹配字符自身
- Exceptions are special characters. 特殊字符不是匹配自身,而是按照如下特殊字符匹配规则匹配
特殊字符匹配规则:
1 | \ Escape special char or start a sequence.转义字符,用于停止特殊字符匹配功能 |
1 | . Match any char except newline, see re.DOTALL 匹配所有字符(不包括换行符) |
1 | ^ Match start of the string, see re.MULTILINE 匹配行开始 |
1 | $ Match end of the string, see re.MULTILINE 匹配行结束 |
1 | [] Enclose a set of matchable chars 列举 |
1 | R|S Match either regex R or regex S. 【|】或 |
1 | () Create capture group, & indicate precedence 分组符 |
1 | ] End the set, if not the first char |
1 | - A range, eg. a-c matches a, b or c 表范围 |
1 | ^ Negate the set only if it is the 1st char 否定 |
Regular Expression Examples
re.findall()
1 | # split all string from a sentence |
Match hex color value
1 | '^#?([a-f0-9]{6}|[a-f0-9]{3})$', '#ffffff') re.match( |
Match username doesn’t have any special characters
1 | '^[a-zA-Z0-9-_]{3,16}$', 'Check') is not None re.match( |
Match email address format
1 | re.match('^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$', |