Python - ^ role in the regular expression

^ There are two roles in a regular expression, one is beginning to express what the second is the expression of what is negated . Occasionally silly I could not tell, then give you details of how to use this ^
prepare a python file test.py, borrow re.search function illustration

# coding=utf-8
import re

S = [ ' ABC-CBA-123 ' ,        # 'ABC' on top 
    ' 123-ABC-123-aabbcc ' , # 'ABC' intermediate 
    ' A-B-2-3. 1- ' ,           # front is 'A' 
    ' bxca-. 1 ' ,           # top is' B ' 
    ' ZA-. 1 ' ,               # ' A 'intermediate 
    ' XYZ ' ,               # string no' A ',' B ',' C ' 
    ' cbaabc '               # string all' a ',' b ','c' composed 
]

st = r'abc'  
for i in s:
    m = re.search(st, i)
    if m:
        print(i)


1. When st = r'abc ', the results obtained were as follows performed python file    
ABC-CBA-123
123-ABC-123-aabbcc
cbaabc
string for the' abc 'on the matching is successful

2. When st = r '[abc]', the results obtained were as follows performed python file    
ABC-CBA-123
123-ABC-123-aabbcc
A-2-3. 1-B-
B-XCA. 1-
Z-A. 1-
cbaabc
string as long as 'a' or 'b' or 'c', it will match

3. When st = r '^ abc', the results obtained were as follows performed python file    
abc-123-cba
string only 'abc' out before the beginning of the match

4. When st = '^ [abc]', the results obtained were as follows performed python file 
ABC CBA-123-
A-B-2-3. 1-
B-XCA. 1-
cbaabc
string of 'a' or 'b' or 'c' at the beginning of the match out

5. When st = '[^ abc]', the results obtained were as follows performed python file 
ABC-CBA-123
123-ABC-123-aabbcc
A-2-3. 1-B-
B-XCA. 1-
Z-A. 1-
X -yz
string as long as the other 'a' and 'b' and 'c' are matched to the characters out, this situation is reversed with the third   
   
summary:
'abc' represents a string for the 'abc' on the match success
'[abc]' represents a string for the 'a' or 'b' or 'c' to match succeeds
'^ abc' represented by the beginning of the string 'abc' can successfully matched
'^ [abc]' represented by a string 'a' or 'b' or 'c' beginning,
'[^ ABC]' matches the characters that are represented by 'a', 'b', 'c'. If a string is 'a', 'b', 'c' are combined, it is false 

When ^ represents the negation of time, only one case, that is, in parentheses, and each character is outside. So do not put '[^ abc]' is regarded as 'abc' string negated.
If you want to 'abc' string negated, the only change the code
ST = r'abc ' 
for I in S:
    m = the re.search (ST, I)
    IF Not m

Commonly include negated:
'[^ AZ]' characters that are all lowercase letters
'[^ a-zA-Z ]' characters than all uppercase and lowercase letters
'[^ 0-9]' all numbers outside character of

If the article there is an error, look to your correction.

Guess you like

Origin www.cnblogs.com/ddzj01/p/10927054.html