Python regular expression
A regular expression is a special sequence of characters that helps you easily check if a string matches a pattern.
Python has added the re module since version 1.5, which provides a Perl-style regular expression pattern.The
re module gives the Python language full of regular expression functionality.The
compile function generates a regular expression object based on a pattern string and optional flag parameters. This object has a set of methods for regular expression matching and replacement.The
re module also provides functions that are fully functional with these methods, using a pattern string as their first argument.
This chapter focuses on regular expression processing functions commonly used in Python.
re.match attempts to match a pattern from the beginning of the string. If the start position is not matched successfully, match() returns none.
re.match Span>(pattern, < /span>string, flags =0)
Function parameter description:
|pattern||matching regular expressions|
|string||The string to match.|
|flags||flag is used to control how regular expressions are matched, such as whether to distinguish between uppercase and lowercase, multi-line matching, and so on. See: Regular Expression Modifiers - Optional Flags|
The matching success re.match method returns a matching object, otherwise it returns None.
We can use the group(num) or groups() matching object functions to get the matching expression.
|Matching object methods||Description|
|group(num=0)||matches the string of the entire expression, group() can enter multiple group numbers at a time, in which case it will return one containing those The tuple of the value corresponding to the group.|
|groups()||Returns a tuple containing all the group strings, from 1 to the included team number.|
The above example runs the output as:
(0, 3) None
The above example execution results are as follows：
matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter