Python3 Regular Expressions

Source: Internet
Author: User
Tags character classes modifier uppercase letter

A regular expression is a special sequence of characters that can help you easily check whether a string matches a pattern.
Python has added the RE module since version 1.5, which provides a Perl-style regular expression pattern.
The RE module enables the Python language to have all the regular expression functionality.
The compile function generates a regular expression object based on a pattern string and an optional flag parameter. The object has a series of methods for regular expression matching and substitution.
The RE module also provides functions that are fully consistent with these methods, which use a pattern string as their first parameter.
This section focuses on the regular expression handlers commonly used in Python.

Re.match function

Re.match attempts to match a pattern from the starting position of the string, and if the match is not successful, match () returns none.
function Syntax:

Re.match (Pattern, string, flags=0)

Function parameter Description:

Parameters Description
Pattern Matched regular Expressions
String The string to match.
Flags A flag bit that controls how regular expressions are matched, such as case sensitivity, multiline matching, and so on.

The match succeeds Re.match method returns a matching object, otherwise none is returned.

We can use the group (NUM) or groups () matching object function to get a matching expression.

Matching Object Methods Description
Group (num=0) A string that matches the entire expression, group () can enter more than one group number at a time, in which case it returns a tuple that contains the corresponding values for those groups.
Groups () Returns a tuple containing all the group strings, from 1 to the included group number.

Example 1:

#!/usr/bin/python#-*-coding:utf-8-*-Import reprint (Re.match (' www ', ' www.runoob.com '). span ())  # matches print at the starting position ( Re.match (' com ', ' www.runoob.com ')         # does not match at start position

The above example runs the output as:

(0, 3) None

Example 2:

#!/usr/bin/python3import reline = "Cats is smarter than dogs" Matchobj = Re.match (R ' (. *) is (. *?). * ', line, re. M|re. I) If matchobj:   print ("Matchobj.group ():", Matchobj.group ())   print ("Matchobj.group (1):", Matchobj.group (1) )   Print ("Matchobj.group (2):", Matchobj.group (2)) Else:   print ("No match!!")

The results of the above instance execution are as follows:

Matchobj.group ():  Cats is smarter than Dogsmatchobj.group (1):  Catsmatchobj.group (2):  Smarter
Re.search method

Re.search scans the entire string and returns the first successful match.
function Syntax:

Re.search (Pattern, string, flags=0)

Function parameter Description:

Parameters Description
Pattern Matched regular Expressions
String The string to match.
Flags A flag bit that controls how regular expressions are matched, such as case sensitivity, multiline matching, and so on.

The match succeeds Re.search method returns a matching object, otherwise none is returned.

We can use the group (NUM) or groups () matching object function to get a matching expression.

Matching Object Methods Description
Group (num=0) A string that matches the entire expression, group () can enter more than one group number at a time, in which case it returns a tuple that contains the corresponding values for those groups.
Groups () Returns a tuple containing all the group strings, from 1 to the included group number.

Example 1:

#!/usr/bin/python3import Reprint (Re.search (' www ', ' www.runoob.com '). span ())  # matches print at the starting position (' com ', ' Www.runoob.com '). span ())         # does not match at the start position

The above example runs the output as:

(0, 3) (11, 14)

Example 2:

#!/usr/bin/python3import reline = "Cats is smarter than dogs"; searchobj = Re.search (R ' (. *) is (. *?). * ', line, re. M|re. I) If searchobj:   print ("Searchobj.group ():", Searchobj.group ())   print ("Searchobj.group (1):", Searchobj.group (1))   print ("Searchobj.group (2):", Searchobj.group (2)) Else:   print ("Nothing found!!")

The results of the above instance execution are as follows:

Searchobj.group ():  Cats is smarter than Dogssearchobj.group (1):  Catssearchobj.group (2):  Smarter
The difference between Re.match and Re.search

Re.match matches only the beginning of the string, if the string does not begin to conform to the regular expression, the match fails, the function returns none, and Re.search matches the entire string until a match is found.
Instance:

#!/usr/bin/python3import reline = "Cats is smarter than dogs"; matchobj = Re.match (R ' Dogs ', line, re.) M|re. I) If matchobj:   print ("match-to-Matchobj.group ():", Matchobj.group ()) Else:   print ("No match!!") Matchobj = Re.search (R ' Dogs ', line, re. M|re. I) If matchobj:   print ("Search-and Matchobj.group ():", Matchobj.group ()) Else:   print ("No match!!")

The results of the above example operation are as follows:

No match!! Search--Matchobj.group ():  dogs
Retrieving and replacing

The Python re module provides re.sub to replace matches in a string.
Grammar:

Re.sub (Pattern, Repl, String, count=0)

Parameters:

    • Pattern: The modal string in the regular.
    • REPL: The 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.

Instance:

#!/usr/bin/python3import Rephone = "2004-959-559 # This is a phone number" # Delete Comment num = re.sub (R ' #.*$ ', "" ", phone) print (" Phone number: ", num) # Remove the contents of num = Re.sub (R ' \d ', "", phone) print ("Phone number:", num) unless the number is

The results of the above instance execution are as follows:

Phone Number:  2004-959-559 phone:  2004959559
The REPL parameter is a function

The matching numbers in the string are multiplied by 2 in the following instance:

#!/usr/bin/pythonimport re# will match the number multiplied by 2def double (matched):    value = Int (Matched.group (' value '))    return str ( Value * 2) s = ' a23g4hfd567 ' Print (Re.sub (? p<value>\d+) ', double, s)

The result of the execution output is:

a46g8hfd1134
Regular expression modifier-optional flag

A regular expression can contain some optional flag modifiers to control the pattern that is matched. The modifier is specified as an optional flag. Multiple flags can be specified by bitwise OR (|). such as Re. I | Re. M is set to the I and M flags:

modifier description
re. I make matching case insensitive
re. L do localization identification (locale-aware) match
re. M multiline match, affecting ^ and $
re. S match all characters including line break
re. U
re. X This flag is given by giving you a more flexible format so that you can write regular expressions much easier to understand.

Regular expression pattern

A pattern string uses a special syntax to represent a regular expression:
Letters and numbers denote themselves. The letters and numbers in a regular expression pattern match the same string.
Most letters and numbers have a different meaning when they are put in front of a backslash.
Punctuation marks only match themselves if they are escaped, otherwise they represent special meanings.
Backslashes themselves need to be escaped with backslashes.
Because regular expressions usually contain backslashes, you might want to use the original string to represent them. The pattern element (such as R '/t ', equivalent to '//t ') matches the corresponding special character.
The following table lists the special elements in the regular expression pattern syntax. If you use the pattern while providing optional flag parameters, the meaning of some pattern elements will change.

Mode Description
^ Matches the beginning of a string
$ Matches the end of the string.
. Matches any character, except the newline character, when re. When the Dotall tag is specified, it can match any character that includes a line feed.
[...] Used to represent a set of characters, listed separately: [AMK] matches ' a ', ' m ' or ' K '
[^...] Characters not in []: [^ABC] matches characters other than a,b,c.
Tel Matches 0 or more expressions.
Re+ Matches 1 or more expressions.
Re? Matches 0 or 1 fragments defined by a preceding regular expression, not greedy
re{N}
re{N,} Exact match n preceding expression.
re{N, m} Matches N to M times the fragment defined by the preceding regular expression, greedy way
a| B Match A or B
(RE) The G matches the expression in parentheses, and also represents a group
(? imx) The regular expression consists of three optional flags: I, M, or X. Affects only the areas in parentheses.
(?-imx) The regular expression closes I, M, or x optional flag. Affects only the areas in parentheses.
(?: RE) A similar (...), but does not represent a group
(? imx:re) Use I, M, or x optional flag in parentheses
(?-imx:re) I, M, or x optional flags are not used in parentheses
(?#...) Comments.
(? = re) Forward positive qualifiers. If a regular expression is included, ... Indicates that a successful match at the current position succeeds or fails. But once the contained expression has been tried, the matching engine is not improved at all, and the remainder of the pattern attempts to the right of the delimiter.
(?! Re) Forward negative qualifier. As opposed to a positive qualifier, when the containing expression cannot match the current position of the string
(?> re) Match the standalone mode, eliminating backtracking.
\w Match Alpha-Numeric
\w Match non-alphanumeric numbers
\s Matches any whitespace character, equivalent to [\t\n\r\f].
\s Match any non-null character
\d Match any number, equivalent to [0-9].
\d Match any non-numeric
\a Match string start
\z Matches the end of the string, if there is a newline, matches only the ending string before the line break. C
\z Match string End
\g Matches the position where the last match was completed.
\b Matches a word boundary, which is the position between a word and a space. For example, ' er\b ' can match ' er ' in ' never ', but not ' er ' in ' verb '.
\b Matches a non-word boundary. ' er\b ' can match ' er ' in ' verb ', but cannot match ' er ' in ' Never '.
\ n, \ t, et. Matches a line break. Matches a tab character. such as
\1...\9 Matches the contents of the nth grouping.
\10 Matches the contents of the nth grouping, if it is matched. Otherwise, it refers to an expression of octal character code.

Regular expression Instances

Character matching

Example Description
Python Match "Python".

Character class

Example Description
[Pp]ython Match "python" or "python"
Rub[ye] Match "Ruby" or "Rube"
[Aeiou] Match any one of the letters within the brackets
[0-9] Match any number. Similar to [0123456789]
[A-z] Match any lowercase letter
[A-z] Match any uppercase letter
[A-za-z0-9] Match any letters and numbers
[^aeiou] All characters except the Aeiou letter
[^0-9] Matches characters except for numbers

Special character Classes

Example Description
. Matches any single character except "\ n". To match any character including ' \ n ', use a pattern like ' [. \ n] '.
\d Matches a numeric character. equivalent to [0-9].
\d Matches a non-numeric character. equivalent to [^0-9].
\s Matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v].
\s Matches any non-whitespace character. equivalent to [^ \f\n\r\t\v].
\w Matches any word character that includes an underscore. Equivalent to ' [a-za-z0-9_] '.
\w Matches any non-word character. Equivalent to ' [^a-za-z0-9_] '.

Python3 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.