Basic Python (11)--Regular expression re module

Source: Internet
Author: User

Security Code: Indifferent Childe


Regular expression (re) is a small, highly specialized programming language that is implemented through the RE module in Python.

Regular expressions can implement the following functions:

Specify rules for the corresponding set of strings that you want to match;

Ability to match an indefinite length of character set;

You can specify the number of repetitions of a part of a regular expression;

You can use re to modify or split strings in various ways

The regular expression pattern is compiled into a sequence of bytecode, which is then executed by the matching engine written by C.

Character matching:

Normal characters:

Most letters and characters will usually match themselves.

If the regular expression test will match the string "test" exactly

Metacharacters

[]:

Used to specify a character set: [ABC] or [A-z]

Metacharacters does not work in the character set: [akm$]

Complement matches characters that are not in range: [^a-z]

^:

Matches the beginning of the line. Unless you set the multiline flag, it just matches the start of the string

In multiline mode, it can also directly match each line break in a string

$

Matches the end of a line, the end of the line is defined as either the end of the string, or any position following a newline character

\:

A backslash can be followed by a different character utilises to denote different special meanings.

can also be used to cancel all metacharacters: \[or \ \

\d: Matches any decimal number: it is equivalent to [0-9]

\d: Matches any non-numeric character: it is equivalent to [^0-9]

\s: Matches any whitespace character: it is equivalent to [\t\n\r\f\v]

\s: Matches any non-whitespace character: it is equivalent to [^\t\n\r\f\v]

\w: Matches any alphanumeric character: it is equivalent to [a-za-z0-9_]

\w: Matches any non-alphanumeric character: it is equivalent to [^a-za-z0-9_]

*:

Specifies that the previous character can be matched 0 or more times instead of only once.

The matching engine tries to repeat as many times as possible (no more than integer scoping, 2 billion)

+

Represents a match at least once or more

?:

Match once or 0 times: You can think of it as an option to identify something

After repetition (+ and *), you can enable lazy mode to achieve a minimum match

{M,n}:

where m and n are decimal integers. The qualifier means at least m duplicates, up to n repetitions

Ignoring m would consider the lower boundary to be 0, while ignoring n would result in an infinity on the upper boundary (actually 2 billion)

{0,} equals *,{1} equals +, while {0,1} is the same as. If possible, it is best to use *, + or?

(): Group

Grouping can divide some data into a whole

When a match is made with FindAll, only the data in the group is returned if there is a grouping

email = R ' \[email protected]\w+\. (com|cn|com\.cn) '

Use regular Expressions:

The RE module provides an interface Re.compile () function for the regular expression engine, which compiles restring into objects and uses them for matching.

The compiled regex is much faster than the regular processing that is interpreted directly without compiling.

Compile the regular expression:

In [1]: Import reIn [2]: Phone_number = re.compile (' ^\d{3,4}-?\d{8}$ ') in [3]: Print phone_number<_sre. Sre_pattern object at 0x7f672ed46300>in [4]: Phone_number.findall (' 010-12345678 ') out[4]: [' 010-12345678 ']In [5]: Phone_number.findall (' 010-123456789 ') out[5]: []in [6]: Phone_number.findall (' 0120-12345678 ') out[6]: [' 0120-12345678 ']

Re.compile () also accepts optional flag parameters, which are commonly used to implement different special functions and syntax changes.

p = re.compile (R ' ab* ', re. IGNORECASE)

Compile flag-flags: The following single letter can replace the previous word, such as re. S can replace Re.dotall

Dotall,s: Make "." The dot number matches all characters including line breaks.

Ignorecase,i: make match case insensitive

Locale,l: Make localization recognition () match. French, etc.

Multiline,m: Multiline match, affects ^ and $. Applies to the case where the text to be matched is distributed across multiple lines.

Verbose,x: The VERBOSE state of RES can be used to make it easier to understand. For hermetical, the expression is distributed in multiple rows.

The trouble with the backslash (\):

Strings with ' R ' backslashes are not handled in any special way

\section: String to match

\\section: Special meaning of removing backslashes for re.compile

"\\\\section": the special meaning of removing backslashes for string real value (string literals) for "\\section"

Perform matching functions that are commonly used:

The ' Regexobject ' instance has some methods and properties, and the complete list is available in the Python Library Reference

Match (): Determines if re is matched at the beginning of the string

Search (): Scans the string to find where the re matches, no matter where in the string it can be found

FindAll (): Find all the substrings that the re matches and return them as a list

Finditer (): Find all the substrings that the re matches and return them as an iterator

Note: Match () and search () will return none if they do not match. Returns a ' Matchobject ' instance object if the match succeeds

Matchobject instance method:

Group (): Returns a string that is matched by re

Start (): Returns the position where the match started

End (): Returns the position where the match ended

Span (): Returns a tuple containing the location of the match (start, end)

In the actual program, the most common method is to save ' matchobject ' in a variable and then check if it is none.

#!/usr/bin/pythonp = Re.compile (...) m = P.match (' string goes here ') if M:print ' match found: ', M.group () else:print ' No match '

module-level functions:

The RE module also provides top-level function calls such as match (), search (), sub (), Subn (), Split (), FindAll (), etc.

Re.sub (Pattern, REPL, String):

Given a regular expression pattern, it acts on a string string and modifies the matching content to Repl

such as: Re.sub (R ' w...d ', ' python ', ' Hello World '), this sentence will be implemented to modify Hello world to Hello python

Re.split (Pattern, String):

Given a regular expression pattern, it acts on a string implementation to split

such as: Re.split (R ' [\+\-\*] ', ' 123+456-789*000 '), split the trailing string with the +-* delimiter

This article is from the "Home" blog, please make sure to keep this source http://itchentao.blog.51cto.com/5168625/1891046

Basic Python (11)--Regular expression re module

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.