"Python3 Re"

Source: Internet
Author: User

First, regular re1. Regular expression definitions

A regular is a way to describe a character or string by combining symbols with special meanings, called regular expressions. Or, the regular is the rule used to describe a class of things. (in Python) it is embedded in Python and is implemented through the RE module. The regular expression pattern is compiled into a sequence of bytecode, which is then executed by a matching engine written in C.

2. Common Regular Expressions

3. Greedy mode and non-greedy mode

Regular expressions are typically used to find matching strings in text. The number of words in Python is greedy by default (which may be the default non-greedy in a few languages), always trying to match as many characters as possible, and not greedy, instead, always trying to match as few characters as possible. For example: the regular expression "ab*" will find "abbb" if it is used to find "ABBBC". And if you use a non-greedy quantity word "ab*?", you will find "a".

4. Back slash

As with most programming languages, "\" is used as an escape character in regular expressions, which can cause a backslash to be plagued. If you need to match the character "\" in the text, then 4 backslashes "\\\\" will be required in the regular expression expressed in the programming language: the first two and the last two are used to escape the backslash in the programming language, converted to two backslashes, and then escaped in the regular expression into a backslash. The native string in Python solves this problem well, and the regular expression in this example can be expressed using R "\ \". Similarly, a "\\d" that matches a number can be written as r "\d". With the native string, you no longer have to worry about missing the backslash, and the expression is more intuitive.

5.re Module

Python provides support for regular expressions through the RE module. The general step for using re is to compile the string form of the regular expression into a pattern instance, then use the pattern instance to process the text and get the matching result (a match instance), and finally use the match instance to get the information and do other things.

Match

The match object is a matching result that contains a lot of information about this match and can be obtained using the readable properties or methods provided by match.

Property:

    1. string: The text to use when matching.
    2. re: The pattern object to use when matching.
    3. POS: The index in which the text expression begins the search. The value is the same as the parameter with the same name as the Pattern.match () and Pattern.seach () methods.
    4. endpos: The index of the end-of-search text expression. The value is the same as the parameter with the same name as the Pattern.match () and Pattern.seach () methods.
    5. lastindex: The index of the last captured grouping in the text. If there are no captured groupings, it will be none.
    6. Lastgroup: The alias of the last captured group. If the group has no aliases or no captured groupings, it will be none.

Method:

    • Group ([Group1, ...]):

Gets the string that is intercepted by one or more groups, and returns a tuple when multiple parameters are specified. Group1 can use numbers or aliases; number 0 represents the entire matched substring; returns Group (0) when no parameters are filled; Groups that have not intercepted a string return none; The group that intercepted multiple times returns the last substring intercepted.

    • Groups ([default]):

Returns the string intercepted by all groups as a tuple. Equivalent to calling group (,... last). Default indicates that a group that does not intercept a string is replaced with this value, which defaults to none.

    • Groupdict ([default]):

Returns a dictionary with aliases for the alias of the group, the value of the substring intercepted by the group, and no alias for the group. The default meaning is the same.

    • Start ([group]):

Returns the starting index of the substring intercepted by the specified group in string (the index of the first character of the substring). The group default value is 0.

    • End ([group]):

Returns the end index of the substring intercepted by the specified group in string (the index of the last character of the substring + 1). The group default value is 0.

    • span ([group]):

Returns (Start (group), End (group)).

    • Expand (Template):

Substituting the matched grouping into the template and then returns. The template can be grouped using \id or \g<id>, \g<name> reference, but cannot use number 0. \id and \g<id> are equivalent, but \10 will be considered a 10th grouping, if you want to express \1 after the character ' 0 ', use only \g<1>0.

Cases:

Import rem = Re.match (R ' (\w+) (\w+) (? p<sign>.*) ', ' Hello world! ') Print ("m.string:", m.string) print ("M.re:", m.re) print ("M.pos:", M.pos) print ("M.endpos:", M.endpos) print (" M.lastindex: ", M.lastindex) print (" M.lastgroup: ", M.lastgroup) print (" M.group: ", M.group (1, 2)) print (" M.groups ( ): ", M.groups ()) Print (" M.groupdict (): ", M.groupdict ()) Print (" M.start (2): ", M.start (2)) print (" M.end (2): ", M.end (2)) Print ("M.span (2):", M.span (2)) print (R "M.expand (R ' \2 \1\3 '):", M.expand (R ' \2 \1\3 '))

Output

M.string:hello world!m.re:re.compile (' (\\w+) (\\w+) (? p<sign>.*) M.pos:0m.endpos:12m.lastindex:3m.lastgroup:signm.group: (' Hello ', ' World ') m.groups (): (' Hello ', ' world ', '! ') M.groupdict (): {' sign ': '! '} M.start (2): 6m.end (2): 11m.span (2): (6, one) M.expand (R ' \2 \1\3 '): World hello!

Pattern

The pattern object is a compiled regular expression that can be matched to the text by a series of methods provided by pattern.

Pattern cannot be instantiated directly and must be constructed using Re.compile ().

The pattern provides several readable properties for getting information about an expression:

    1. Pattern: The expression string used at compile time.
    2. Flags: The matching pattern used at compile time. Digital form.
    3. Groups: The number of groupings in an expression.
    4. Groupindex: The alias of the group with the alias in the expression is the key, the dictionary with the number corresponding to that group, and the group without the alias is not included.

Cases:

Import rep = Re.compile (R ' (\w+) (\w+) (? p<sign>.*) ', Re. Dotall) Print ("P.pattern:", P.pattern) print ("P.flags:", p.flags) print ("P.groups:", p.groups) print ("P.groupindex:", P.groupindex)

Output

P.pattern: (\w+) (\w+) (? p<sign>.*) P.flags:48p.groups:3p.groupindex: {' sign ': 3}

instance method [| Re module Method]:

    • Match (string[, pos[, Endpos]) | Re.match (pattern, string[, flags]):

This method attempts to match pattern from the POS subscript of string, returns a match object if pattern is still matched at the end, or none if pattern does not match during the match, or if the match does not end with Endpos.

The default values for POS and Endpos are 0 and Len (string), Re.match () cannot specify these two parameters, and the parameter flags specifies the matching pattern when compiling pattern.

Note: This method is not an exact match. If the string has any remaining characters at the end of the pattern, it is still considered successful. If you want an exact match, you can add the boundary match ' $ ' at the end of the expression.

See section 2.1 for an example.

    • Search (string[, pos[, Endpos]) | Re.search (pattern, string[, flags]):

This method is used to find substrings in a string that can match a success. Attempts to match the pattern from the POS subscript of string, returns a match object if the pattern ends with a match, and tries to match the POS after 1 if it does not match, and returns none until Pos=endpos is still not matched.
The default values for POS and Endpos are 0 and Len (string), and Re.search () cannot specify both parameters, and the parameter flags specify a matching pattern when compiling pattern.

Import re# compiles a regular expression into a pattern object pattern = Re.compile (R ' World ') # using Search () to find a matching substring, no substring to match will be returned none# This example uses match () Could not successfully match matches = Pattern.search (' Hello world! ') If match:    # use Match to get Group Info    print (Match.group ())

Output

World

    • Split (string[, Maxsplit]) | Re.split (Pattern, string[, Maxsplit]):

Returns a list after splitting a string by a substring that can be matched. The maxsplit is used to specify the maximum number of splits and does not specify that all will be split.

Import rep = Re.compile (R ' \d+ ') print (P.split (' One1two2three3four4 '))

Output

[' One ', ' one ', ' three ', ' four ', ']

    • FindAll (string[, pos[, Endpos]) | Re.findall (pattern, string[, flags]):

Searches for a string, returning all matching substrings as a list.

Import rep = Re.compile (R ' \d+ ') print (P.findall (' One1two2three3four4 '))

Output

[' 1 ', ' 2 ', ' 3 ', ' 4 ']

    • Finditer (string[, pos[, Endpos]) | Re.finditer (pattern, string[, flags]):

Searches for a string that returns an iterator that accesses each matching result (match object) sequentially.

Import rep = Re.compile (R ' \d+ ') for M in P.finditer (' One1two2three3four4 '):    print (M.group (),)

Output

1234

    • Sub (repl, string[, Count]) | Re.sub (Pattern, REPL, string[, Count]):

Returns the replaced string after each matched substring in string is replaced with REPL.
When Repl is a string, you can use \id or \g<id>, \g<name> reference grouping, but you cannot use number 0.
When Repl is a method, this method should only accept one parameter (the match object) and return a string for substitution (the returned string cannot be referenced in the grouping).
Count is used to specify the maximum number of replacements, not all when specified.

Import rep = Re.compile (R ' (\w+) (\w+) ') s = ' I say, hello world! ' Print (P.sub (R ' \2 \1 ', s)) def func (m):    return M.group (1). Title () + "+ m.group (2)." Title () print (P.sub (func, s))

Output

Say I, World hello! I Say, Hello world!

    • Subn (REPL, string[, Count]) |re.sub (pattern, REPL, string[, Count]):

Returns (Sub (REPL, string[, Count]), number of replacements).

Import rep = Re.compile (R ' (\w+) (\w+) ') s = ' I say, hello world! ' Print (P.subn (R ' \2 \1 ', s)) def func (m):    return M.group (1). Title () + "+ m.group (2)." Title () print (P.subn (func, s))
(' Say I, World hello! ', 2) (' I Say, Hello world! ', 2)

    • Re.compile (strpattern[, flag]):

This method is the factory method of the pattern class, which compiles a regular expression in the form of a string into a pattern object. The second parameter, flag, is the matching pattern, and the value can use the bitwise OR operator ' | ' To take effect at the same time, such as re. I | Re. M. Alternatively, you can specify patterns in the Regex string, such as re.compile (' pattern ', re. I | Re. M) is equivalent to Re.compile (' (? im) pattern ').
The optional values are:

    • Re. I (re. IGNORECASE): Ignore case (full notation in parentheses, same as below)
    • M (MULTILINE): Multiline mode, changing the behavior of ' ^ ' and ' $ ' (see)
    • S (dotall): Point any matching pattern, change '. ' The behavior
    • L (LOCALE): Make a predetermined character class \w \w \b \b \s \s depends on the current locale setting
    • U (UNICODE): Make a predetermined character class \w \w \b \b \s \s \d \d Depending on the UNICODE-defined character attribute
    • X (VERBOSE): Verbose mode. In this mode, the regular expression can be multiple lines, ignore whitespace characters, and can be added to comments. The following two regular expressions are equivalent:
A = Re.compile (r "" "\d +  # the integral part                   \.    # The decimal point                   \d *  # some fractional digits "", Re. X) b = Re.compile (r "\d+\.\d*")

Re provides a number of modular methods for completing regular expression functions. These methods can be substituted with the corresponding method of the pattern instance, with the only advantage being that one less line of Re.compile () code is written, but the compiled pattern object cannot be reused at the same time. These methods are described in the example Method section of the pattern class. As the above example can be abbreviated as:

m = Re.match (R ' Hello ', ' Hello world! ') Print (M.group ())

The RE module also provides a method of escape (string), which is used to such as the regular expression metacharacters in string */+/, and so on before the escape character is returned, which is a bit more useful when a large number of matching metacharacters are required.

6. Examples of commonly used matching methods

    • \w and \w
Import reprint (Re.findall (' \w ', ' Hello hexin 123 ')) Print (Re.findall (' \w ', ' Hello hexin 123 '))

Output

[' H ', ' e ', ' l ', ' l ', ' o ', ' h ', ' e ', ' x ', ' I ', ' n ', ' 1 ', ' 2 ', ' 3 '] [‘ ‘, ‘ ‘]

    • \s and \s
Import reprint (Re.findall (' \s ', ' Hello  hexin  123 ')) Print (Re.findall (' \s ', ' Hello  hexin  123 '))

Output

[‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘] [' H ', ' e ', ' l ', ' l ', ' o ', ' h ', ' e ', ' x ', ' I ', ' n ', ' 1 ', ' 2 ', ' 3 ']

    • \d and \d
Import reprint (Re.findall (' \d ', ' Hello hexin 123 ')) Print (Re.findall (' \d ', ' Hello hexin 123 '))

Output

[' 1 ', ' 2 ', ' 3 '] [' H ', ' e ', ' l ', ' l ', ' o ', ' ', ' h ', ' e ', ' x ', ' I ', ' n ', ']

    • \a and \z
Import reprint (Re.findall (' \ahe ', ' Hello hexin 123 ')) Print (Re.findall (' 123\z ', ' Hello hexin 123 '))

Output

[' He '] [' 123 ']

    • \ n and \ t
Import Reprint (Re.findall (R ' \ n ', ' Hello hexin \n123 ')) print (Re.findall (R ' \ t ', ' Hello Heixn \t123 '))

Output

[' \ n '] [' \ t ']

    • ^ with $

Output

[' H '] [' 3 ']
    • Repeat match: |. | * | ? | .* | .*? | + | {N,m} |

Output

[' A1B '] [] [' A\NB '] [' A\NB ']

    • *

Output

[[' A ']

    • ?

Output

[' A '] [' AB ']

    • Match all numbers that contain decimals
Import reprint (Re.findall (' \d+\.? \d* ', "asdfasdf123as1.13dfa12adsf1asdf3"))

Output

[' 123 ', ' 1.13 ', ' 12 ', ' 1 ', ' 3 ']

    • . * Default is greedy match
Print (Re.findall (' a.*b ', ' a1b22222222b '))

Output

[' a1b22222222b ']

    • . *? For non-greedy matches
Import reprint (Re.findall (' a.*?b ', ' a1b22222222b '))

Output

[' A1B ']

    • +
Import reprint (Re.findall (' ab+ ', ' a ')) print (Re.findall (' ab+ ', ' abbb '))

Output

[[' ABBB ']

    • {N,m}

Output

[' ABB '] [' ABBB '] [' ABBB '] [' ABBB ']

    • []
Import reprint (Re.findall (' a[1*-]b ', ' a1b a*b A-B ')) are all ordinary characters, and if-not converted, should be placed at the beginning or end of [] print (#[(' Re.findall ') B ', ' a1b a*b-A-a=b ') (#[]) ^ means to take anti-print (Re.findall (' a[0-9]b ', ' a1b a*b A-b a=b ') #[] within the ^ represents the meaning of "take anti-print" (Re.findall (' a[ A-z]b ', ' a1b a*b A-B a=b AEB ')] within the ^ represents the meaning of the ^ is to take the anti-print (#[(' Re.findall ', ' A[a-za-z]b a1b A-b a*b aeb AEB ')) within the ^ represented by the ^ means take the reverse

Output

[' a1b ', ' a*b ', ' A-B '] [' A=b '] [' A1B '] [' AEB '] [' AEB ', ' AEB ']

    • ()
Import reprint (Re.findall (' ab+ ', ' ababab123 ')) print (Re.findall (' (AB) +123 ', ' ababab123 ')) #匹配到末尾的ab123中的abprint ( Re.findall (' (?: AB) +123 ', ' ababab123 ')) #findall的结果不是匹配的全部内容, but the content within the group?: You can make the result match everything

Output

[' AB ', ' ab ', ' AB '] [' AB '] [' ababab123 ']

    • \
Print (Re.findall (' a\\c ', ' a\c ')) #对于正则来说a \\c can indeed match to a\c, but when the Python interpreter reads a\\c, it escapes and then goes to re to execute, so throw an exception print ( Re.findall (R ' a\\c ', ' a\c ')) #r代表告诉解释器使用rawstring, that is, the native string, all the symbols in our regular character are treated as ordinary characters, do not escape print (Re.findall (' a\\\\c ', ' a\c ') #同上面的意思一样, and the results above are [' a\\c ']

Output

[] [' a\\c '] [' a\\c ']

    • |
Import re
Print (Re.findall (' Compan (y|ies) ', ' Too many companies has gone bankrupt, and the next one is my company ')

Print (Re.findall (' Compan (?: y|ies) ', ' Too many companies has gone bankrupt, and the next one is my company ')) # (?:) Match complete

Output

[' ies ', ' y ']
[' Companies ', ' company ']

Add:

Number Matching

Import Reprint (Re.findall (R '-?\d+\.? \d* ', "1-12* (60+ ( -40.35/5)-( -4*3))") #找出所有数字 [' 1 ', ' -12 ', ', ' -40.35 ', ' 5 ', '-4 ', ' 3 '] #使用 |, first matching the Mister Effect, | The left is a matching decimal, and findall the end result is to look at the grouping, all even if the matching success of the decimal will not be stored in the result # instead of the decimal, to match (-?\d+), the match to the nature is, the number of non-decimals, here is the integer print (Re.findall (r "-?\d+\.\d*| ( -?\d+) "," 1-2* (60+ ( -40.35/5)-( -4*3))) #找出所有整数 [' 1 ', '-2 ', ' 60 ', ' ', ' 5 ', '-4 ', ' 3 ']

Summarize:
Try to use the pan-match pattern. *
Try to use non-greedy mode:. *?
Use parentheses to get a matching target: use Group (n) to obtain results
With a newline character, use re. S: Modify Mode

Easy to use module

Import Re#1print (Re.findall (' e ', ' He Make Love ')   #[' e ', ' e ', ' e '], return all results that meet the matching criteria, put in the list #2print (' E ', ' he Make Love '). Group ()) #e, to find the first match and return an object that contains matching information, the object can get a matching string by calling the group () method, or None if the string does not match. #3print (Re.match (' e ', ' He makes Love ')    #None, same as search, but at the beginning of the string, you can use search+^ instead of Match#4print (Re.split (' [AB] ' ABCD '))     #[', ' ', ' CD ', First press ' a ' to split ' and ' BCD ', then ' and ' BCD ' separately by ' B ' split #5print (' ===> ', re.sub (' A ', ' a ', ' he make Love ') ) #===> He make love, do not specify N, default replaces all print (' ===> ', re.sub (' A ', ' a ', ' he Make Love ', 1)) #===> He make loveprint (' = = = > ', re.sub (' A ', ' a ', ' he Make Love ', 2)) #===> He make loveprint (' ===> ', re.sub (' ^ (\w+) (. *?\s) (\w+) (. *?\s) (\w+) ( .*?) $ ', R ' \5\2\3\4\1 ', ' He Make Love ') #===> love Make Heprint (' ===> ', re.subn (' A ', ' a ', ' he Make Love ')) #===> (' He mAk E love ', 2), results with a total number of replacements #6obj=re.compile (' \d{2} ') Print (Obj.search (' abc123eeee '). Group ()) #12print (Obj.findall (' Abc123eeee ')) (#[' 12 '), with the reuse of obj

Output

[' E ', ' e ', ' e ']enone[', ', ' CD ']===> he make love===> he make love===> he make love===> love make he===> (' He Make Love ', 1) 12[' 12 '

"Python3 Re"

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.