Python Regular Expressions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.