Python Regular Expressions

Source: Internet
Author: User

Regular ExpressionsApplication Scenarios
    • Search for a particular pattern string, replace cut, etc.

    • Validation of formats such as mailbox formats, URLs, etc.

    • Crawler projects to extract specific valid content

    • Configuration files for many applications

Principles of Use
    • Do not use regular as long as it can be solved by related functions such as strings.

    • Regular execution efficiency is lower, which reduces the readability of the Code

    • The world's most difficult to read three things: the Doctor's prescription, the priest's divine symbol, the code farmer's regular

    • Remind: Regular is used to write, not to read, do not try to read others ' regular, do not understand the function when necessary to read the regular.

Basic Use
  • Note: The regular is supported through the RE module

  • Related functions:

    • Match: Matches from the beginning, finds immediately returns the regular result object, no returns None

    • Search: Match all content, anywhere, as soon as found, return the regular result object immediately, no return none

      # Python relies on the secondary module to complete the regular function
      ImportRe
      ?
      # Match from the beginning, find an immediate return to the regular result object, no return None
      m =Re.Match' ABC ', ' ABCHELLOABC ')
      # matches everything, anywhere, as soon as it is found, returns the regular result object immediately, without returning none
      m = re. search ( ' abc ', ' HELLOABCSHSJSLDJ ')
      if m:
          Print (    # get matching content
         print (m.group ())
         # get match location
         print (m.span ())
    • FindAll: Matches all content, returns a list of matching results, does not return none


      # matches all content, returns a list of matching results, no return None
      Re. findall (' abcsdisuoiabcsjdklsjabc ')
      F:
      print (f)
    • Compile: An object that generates a regular expression based on a string for a specific regular match, matched by match, search, FindAll


      # an object that generates a regular expression based on a string for a regular match
      c = re. compile ( ' abc ')
      # then make a specific regular match
      # m = C.match (' abcdefghijklmn ')
      m = c.search ( ' abcdefghijklmn ')
      Span class= "Cm-keyword" >if m:
         print ( Span class= "cm-variable" >m)
      ?
      print (c.findall (

      The process of the match, search, and FindAll methods in the RE module is divided into two steps.

Regular Rules
  • Single character


    Normal character: one-to-one exact match
    []: Any one of the characters in the middle
    [A-z]: Any character representing A to Z
    [0-9]: Any character representing 0 to 9
    [^ABC]: characters other than ABC
    . : matches any character other than ' \ n '
    \d: All numeric characters, equivalent to [0-9]
    \d: All non-numeric characters, equivalent to [^0-9]
    \w: All numbers, letters, Chinese, underscores, etc. (meaning of the word)
    All characters except the \w:\w
    \s: All whitespace characters, such as: space, \ t, \ n, \ r
    All characters except the \s:\s
    \b: Word boundaries, such as: opening, ending, punctuation, spaces, etc.
    \b: Non-word boundary
  • Frequency control


    *: The preceding character can be any time
    +: The preceding character appears at least once
    ?: At most one time, 0 or 1 times
    {m}: matches fixed M-Times
    {m,}: at least m times
    {M,n}:m to n times

    Regular matches are greedy by default.

  • Boundary limit

      • ^: Start with the specified content

      • $: Ends with the specified content


    ImportRe
    ?
    # start with the specified content
    # C = re.compile (R ' ^abc ')
    # to specify end of content
    Span class= "Cm-comment" ># C = re.compile (R ' abc$ ')
    # also limits the beginning and end of
    c = re. Compile (r ' ^abc$ ')
    ?
    s = c.search ( ' abc ')
    ?
    if s:
        Print ( "OK")
       print ( s.group ())
  • Group Matching

      • |: Represents or, with the lowest priority

      • (): Used to represent a whole, can determine priority


    import re
    ?
    # | represents or, with the lowest priority
    # () is used to represent a whole, which can be determined by priority
    Span class= "cm-variable" >c = re. Compile (r ' A (hello|world) d ')
    ?
    s = c.search ( ' aworldd ')
    ?
    if s:
        Print ( "OK")
       print ( s.group ())

    () There is also the role of group matching, next time.

Practice:
    • What to do if you match a character with a special regular meaning, such as: \d

      • Friendly tip: Escape problem (Python relay once, regular parse escape once)

    • Verify that a string is the correct mailbox format

    • Verify that a string is the correct URL format

Ideas
    • Function-oriented

    • Write out several strings that match the rules

    • Write a little bit of measurement, keep adjusting.

    • Final Completion function

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.