Copy codeThe Code is as follows:
#-*-Coding: cp936 -*-
Import re
S1 = 'adkdk'
S2 = 'abc123efg'
An = re. search ('^ [a-z] + $', s1)
If:
Print 's1: ', an. group (), 'all lowercase'
Else:
Print s1, "all lowercase! "
An = re. match ('[a-z] + $', s2)
If:
Print 's2: ', an. group (), 'all lowercase'
Else:
Print s2, "Not all lowercase! "
1. Regular Expressions are not part of python. When using them, you need to reference the re module.
2. The matching format is re. search (Regular Expression with matching string) or re. match (Regular Expression with matching string ). The difference between the two is that the latter starts with the start character (^) by default. Therefore,
Re. search ('^ [a-z] + $', s1) is equivalent to re. match ('[a-z] + $', s2)
3. If the match fails, an = re. search ('^ [a-z] + $', s1) returns None.
Group is used to group matching results.
Copy codeThe Code is as follows:
Import re
A = "123abc456"
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (0) #123abc456, returns the whole
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (1) #123
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (2) # abc
Print re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (3) #456
1) in the regular expression, the matching results are divided into three groups by three sets of parentheses.
Group () and group (0) are the results of matching the regular expression.
Group (1) lists the Matching Parts of the first bracket, group (2) lists the Matching Parts of the second bracket, and group (3) lists the matching parts of the third bracket.
2) If no matching is successful, re. search () returns None
3) Of course, Zheng's expression does not contain parentheses, and group (1) is definitely incorrect.