Python Regular Expressions

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

Python Regular Expressions

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.

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.









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.










Print"Regular Expression ==========================="ImportRePrint(Re.match ('www','www.runoob.com'). span ())#match at start positionPrint(Re.match ('com','www.runoob.com'))#Do not match at start positionImportreline="Cats is smarter than dogs"Matchobj= Re.match ('(. *) is (. *?). *', line, re. m|Re. I)ifMatchobj:Print "Matchobj.group ():", Matchobj.group ()Print "Matchobj.group (1):", Matchobj.group (1) Print "Matchobj.group (2):", Matchobj.group (2)Else: Print "No match!!"ImportRePrint(Re.search ('www','www.runoob.com'). span ())#match at start positionPrint(Re.search ('com','www.runoob.com'). span ())#Do not match at start positionPrint "==========================="Importreline="Cats is smarter than dogs"; Searchobj= Re.search (r'(. *) is (. *?). *', line, re. m|Re. I)ifSearchobj:Print "Searchobj.group ():", Searchobj.group ()Print "Searchobj.group (1):", Searchobj.group (1) Print "Searchobj.group (2):", Searchobj.group (2)Else: Print "Nothing found!!" ImportRe line="Cats is smarter than dogs"; Matchobj= Re.match (r'Dogs', line, re. M |Re. I)ifMatchobj:Print "match--matchobj.group ():", Matchobj.group ()Else: Print "No match!!"Matchobj= Re.search (r'Dogs', line, re. M |Re. I)ifMatchobj:Print "Search--Matchobj.group ():", Matchobj.group ()Else: Print "No match!!"Print "retrieving and replacing ==========================="ImportRephone="2004-959-559 # This is a foreign phone number"#Delete a python comment from a stringnum = Re.sub (r'#.*$',"", phone)Print "The phone number is:", Num#Delete A string that is not a number (-)num = Re.sub (r'\d',"", phone)Print "The phone number is:", NumPrint "parameter is a function =========================="ImportRe#multiply the number of matches by 2defdouble (matched): Value= Int (Matched.group ('value')) returnSTR (Value * 2) s='a23g4hfd567'Print(Re.sub ('(? p<value>\d+)', double, s))

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 the match case insensitive
Re. L Do localization identification (locale-aware) matching
Re. M Multiline match, affecting ^ and $
Re. S Make. Match all characters, including line breaks
Re. U Resolves characters based on the Unicode character set. This sign affects \w, \w, \b, \b.
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 alphanumeric and underline
\w Match non-alphanumeric and underline
\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 A sub-expression that matches the nth grouping.
\10 Matches the sub-expression of the nth grouping if it is matched. Otherwise, it refers to an expression of octal character code.
Regular expression Instance 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_] '.

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.