The Re.match () function only detects if the re is matched at the start of the string
Re.match () returns only if the 0 position match succeeds, and match () returns none if the match is not successful.
# syntax # Re.match (pattern, string, flags=0)
# Eg_v1import rematch = "https://www.python.org" Print (Re.match ("http", match). Span ()) # span () returns a tuple containing a match (start, end) Position # (0, 4) print (Re.match ("www", Match)) # None
The Re.search function looks for pattern matching within a string until the first match is found and then returns if the string does not match, and none is returned.
# syntax # Re.search (pattern, String, flags=0) # Eg_v2import reprint (Re.search ("https", "https://www.baidu.com"). span ()) # (0 , 5) Print (Re.search ("Baidu", "https://www.baidu.com"). span ()) # (12, 17)
re.sub function, Re.sub used to replace matches in a string
# syntax: # re.sub (Pattern, Repl, String, count=0, flags=0) # parameter: # pattern: pattern string in regular. # Repl: A replacement string, or a function. # string: The original string to be looked up for replacement. # count: The maximum number of times a pattern match is replaced, and the default of 0 means that all matches are replaced. # Eg_v3import retxt = "A man was known by the silence He keeps" print (Re.sub (r "\s+", "_", txt) # A_man_is_known_by_the_silenc E_he_keeps
Re.compile function to compile regular expressions into a regular expression object
# syntax # re.compile (pattern, flags=0) # Eg_v4import RETSXT = "Happiness is on the doing, right?" The Getting what do you want. " Regex = Re.compile (r "\w*do\w*") Print (Regex.findall (TSXT)) #查找所有包含 ' do ' word # [' doing ']print (Regex.sub (lambda m: "[ "+ m.group (0) +"] ", TSXT)) #将字符串中含有 ' do ' words are enclosed in [] # happiness are in the [doing], right? The Getting what do you want.
Python Regular Expressions