def match (pattern, string, flags=0):
"" "Try to apply the pattern at the start of the string, returning
A match object, or None if no match was found. "" "
return _compile (pattern, flags). Match (String)
Import re
Print (Re.match (' www ', ' www.baidu.com '))
Results: <_sre. Sre_match object; Span= (0, 3), match= ' www ' >
Print (Re.match (' www ', ' www.baidu.com '). Group ())
Results: www
Print (Re.match (' w.b ', ' www.baidu.com '))
Result: None
Conclusion: Match the starting string and return an object with the group () method to see the result of the match
def fullmatch (pattern, String, flags=0):
"" "Try to apply the pattern to all of the string, returning
A match object, or None if no match was found. "" "
return _compile (pattern, flags). Fullmatch (String)
Print (Re.fullmatch (' www.baidu.com ', ' www.baidu.com '). Group ())
Results: www.baidu.com
Print (Re.fullmatch (' www ', ' www.baidu.com '))
Result: None
def search (pattern, String, flags=0):
"" "Scan through string looking for a match to the pattern, returning
A match object, or None if no match was found. "" "
return _compile (pattern, flags). Search (String)
Print (Re.search (' w.b ', ' www.baidu.com '))
Results: <_sre. Sre_match object; Span= (2, 5), match= ' w.b ' >
Print (Re.search (' w.b ', ' www.baidu.com '). Group ())
Results: w.b
Print (Re.search (' WWA ', ' www.baidu.com '))
Result: None
def sub (pattern, REPL, String, count=0, flags=0):
"" "Return the string obtained by replacing the leftmost
Non-overlapping occurrences of the pattern in string by the
Replacement repl. REPL can be either a string or a callable;
If a string, backslash escapes in it is processed. If it is
A callable, it ' s passed the match object and must return
A replacement string to is used. "" "
return _compile (pattern, flags). Sub (repl, string, count)
Import re
Inputstr = "Hello 111 world 222"
Outputstr = Re.sub ("\d+", "333", Inputstr)
Print (OUTPUTSTR)
Result: Hello 333 World 333
Inputstr = "Hello 111 world 222 Hello hello hello hello"
Outputstr = Re.sub ("(Llo)", "333", inputstr,2)
Print (OUTPUTSTR)
Results: he333 111 World 222 he333 Hello Hello hello
import re;
INPUTSTR = "hello-111 World 222"
Outputstr = Re.sub ("\w+-\d+", "333", Inputstr)
Print (OUTPUTSTR)
Result: 333 World 222
Conclusion: \w+ represents a string of letters or numbers, and \d+ represents at least one number-a connector in the middle-
INPUTSTR = "hello-111 World 222"
Outputstr = Re.sub ("[a-za-z]\w*", "333", Inputstr)
Print (OUTPUTSTR)
Results: 333-111 333 222
Conclusion: The front is a letter, followed by a letter or a number
Inputstr = "hello-111-222"
Outputstr = Re.sub ("\d{3}-\d{3}", "333", Inputstr)
Print (OUTPUTSTR)
Results: hello-333
Conclusion: three digits, three digits, intermediate-connected.
INPUTSTR = "[Email protected]"
Outputstr = Re.sub ("\[email protected]\w+\.com", "333", Inputstr)
Print (OUTPUTSTR)
Results: 333
Python Regular Expressions