Summary
In regular expressions, if a character is given directly, it is exactly the exact match.
{m,n}?Repeat to the previous character m n , and take as few cases as possible in the string ‘aaaaaa‘ , a{2,4} matching 4 a , but a{2,4}? only 2 matches a .
^Represents the beginning of a row, ^\d indicating that a number must begin.
$Represents the end of a line, indicating that it \d$ must end with a number.
You may have noticed that you py can also match-up ‘python‘ py ;
But the addition becomes ^py$ the whole line match, can only match ' the Py ', ‘python‘ when matches, can not get anything.
Reference table regular Expression special sequence
Re module
re.compile(pattern[, flags])
Converts the pattern and identity of regular expressions into regular expression objects for match() search() use with these two functions.
The flags defined by re include:
# ’后面的注释
The following two usage results are the same: (A)
compiled_pattern = re.compile(pattern) result = compiled_pattern.match(string)
B
result = re.match(pattern, string)
s = ‘ABC\\-001‘ # Python的字符串 #对应的正则表达式字符串变成: #‘ABC\-001‘
Therefore, we strongly recommend that you use the Python R prefix without considering escaping the problem.
r‘ABC\-001‘ # Python的字符串# 对应的正则表达式字符串不变:# ‘ABC\-001‘
Search
Re.search (pattern, string[, flags]) '
Finds the position in the string that matches the regular expression pattern, returns MatchObject the instance, or returns if no matching position is found None .
For compiled regular expression objects (re.RegexObject) , the following methods are available search :
search (string[, pos[, endpos]])
If regex It is a compiled regular expression object, it is regex.search(string, 0, 50) equivalent to regex.search(string[:50], 0) .
>>> pattern = re.compile("a") >>> pattern.search("abcde") # Match at index 0 >>> pattern.search("abcde", 1) # No match;
Match
Re.match (pattern, string[, flags])
Determines whether the pattern matches at the beginning of the string. For Regexobject, there are:
Match (string[, pos[, Endpos])
The match () function attempts to match the regular expression only at the beginning of the string, that is, only the match that starts at position 0 is reported, and the search () function scans the entire string to find a match. If you want to search the entire string for a match, you should use Search ().
>>> pattern.match(‘bca‘,2).group()‘a‘
Although, the match default is to match from the beginning, but if you specify a location, you can still succeed; matchIt's also the difference between starting a match from the specified position and still failing the mismatch search .
match()The method determines whether the match is successful, returns an object if the match succeeds, Match or returns None .
‘用户输入的字符串‘if re.match(r‘正则表达式‘, test): print(‘ok‘)else: print(‘failed‘)
Split
Re.split (Pattern, string[, maxsplit=0, flags=0])
This feature is often used to split the part of a string-matching regular expression and return a list. For Regexobject, there are functions:
Split (string[, maxsplit=0])
Split does not split a string that cannot find a match
>>> ‘a b c‘.split(‘ ‘)[‘a‘, ‘b‘, ‘‘, ‘‘, ‘c‘]
There is no flexibility in the way the string comes in split .
>>> re.split(r‘\s+‘, ‘a b c‘)[‘a‘, ‘b‘, ‘c‘]
See the difference, very powerful! One more Ultimate:
>>> re.split(r‘[\s\,\;]+‘, ‘a,b;; c d‘)[‘a‘, ‘b‘, ‘c‘, ‘d‘]
r‘[\s\,\;]+‘The regular expression of 式意思为:空格或者 或者 ; ' appears 1 or more times or more than 1 times to meet the conditions of the split symbol! So, the final result is still very clean.
FindAll
re.findall(pattern, string[, flags])
Finds all substrings that match the regular expression in the string and makes up a list to return. RegexObject There are also:
findall(string[, pos[, endpos]])
#get all content enclosed with [], and return a list >>> pattern=re.compile(r‘hh‘)>>> pattern.findall(‘hhmichaelhh‘)[‘hh‘, ‘hh‘]
Finditer
re.finditer(pattern, string[, flags])
And findall Similarly, finds all substrings that match the regular expression in the string and makes up an iterator to return. RegexObjectThere are also:
finditer(string[, pos[, endpos]])
Sub
re.sub(pattern, repl, string[, count, flags])
stringfinds all substrings in the string that match the regular expression pattern , replacing them with another string repl . If no matching string is found pattern , a string that has not been modified is returned. Repl can be either a string or a function.
The return value is the new string after replacement.
For RegexObject A:
Sub (REPL, string[, count=0])
>>> pattern=re.compile (r ' \d ') >>> pattern.sub ( ' no ', ' 12hh34hh ') ' nonohhnonohh ' >>> pattern.sub ( ' No ', ' 12hh34hh ', 0) ' nonohhnonohh ' >>> pattern.sub ( ' no ', 12hh34hh ', Count=0) ' nonohhnonohh ' >>> pattern.sub ( ' no ', ' 12hh34hh ', 1) ' no2hh34hh '
As can be seen from the above example, the count default value is 0, which means replace all;
Subn
re.subn(pattern, repl, string[, count, flags])
The function has the same function as a sub (), but it also returns the new string and the number of substitutions. RegexObject There are also:
subn(repl, string[, count=0])
>>> pattern.subn(‘no‘,‘12hh34hh‘,count=0)(‘nonohhnonohh‘, 4)
Group
In addition to simply judging whether a match is matched, the regular expression also has the power to extract substrings. The group (group) to be extracted is represented by (). Like what:
^(\d{3})-(\d{3,8})$Two groups are defined separately, and the area code and local numbers can be extracted directly from the matching string:
>>> m = Re.match (r ' ^ ( \D{3})-(\d{3,8}) $ ', ' 010-12345 ') >>> m<_sre. Sre_match object; span= (0, 9), Match= ' 010-12345 ' > >>> m.group (0) ' 010-12345 ' >>> m.group (1) ' 010 ' Span class= "Hljs-prompt" >>>> m.group (2) ' 12345 ' >>> m.groups () ( ' 010 ', ' 12345 ')
Through the experiment, if you do not use parentheses, the resulting Match object class can be used such as A.group (0) or a.group () However, using A.group (1) will be an error.
Greedy match
A regular match is a greedy match by default, which is to match as many characters as possible. For example, match the following numbers 0 :
>>> re.match(r‘^(\d+)(0*)$‘, ‘102300‘).groups()(‘102300‘, ‘‘)
Because \d+ of the greedy match, directly the back of 0 all matching, the result 0* can only match the empty string.
\d+a non-greedy match (that is, as few matches as possible) must be used in order to match the latter 0 and add a ? \d+ non-greedy match to it:
>>> re.match(r‘^(\d+?)(0*)$‘, ‘102300‘).groups()(‘1023‘, ‘00‘)
Python Regular Expression Learning resources
- Liaoche-Regular Expressions
- ibm-using the Python module re for parsing gadgets
- deerchao-Expression 30-minute introductory tutorial
- deerchao-Regular Expression 30-minute introductory tutorial
- Static Find-crawler entry seven regular expression
Original link:--by Michael Xiang
Python Regular Expression learning summary and data