Python Regular Expression Basics

Source: Internet
Author: User

Python Regular Expression Basics

Regular Expressions are powerful tools used to process strings. They are not part of Python.

Other programming languages also have the concept of regular expressions. The difference is that different programming languages support different syntaxes.

It has its own unique syntax and an independent processing engine. in languages that provide regular expressions, the regular expression syntax is the same.

The following figure shows the matching process using a regular expression:

1.1 Introduction

Regular expressions are not part of Python. Regular Expressions are powerful tools used to process strings. They have their own unique syntax and an independent processing engine, which may not be as efficient as the built-in str method, but are very powerful. Thanks to this, in languages that provide regular expressions, the syntax of regular expressions is the same. The difference is that different programming languages support different syntaxes, unsupported syntax is usually not commonly used.

A regular expression is a special character sequence that helps you easily check whether a string matches a certain pattern. Python has added the re module since version 1.5. It provides the Perl-style regular expression mode. The re module enables the Python language to have all the regular expression functions.

1.2 usage

The pattern string uses special syntax to represent a regular expression:

Letters and numbers indicate themselves. The letters and numbers in a regular expression match the same string. When a backslash is added before most letters and numbers, it has different meanings. Punctuation marks match themselves only when they are escaped. Otherwise, they indicate special meanings. The backslash itself must be escaped using the backslash.

Since regular expressions usually contain backslashes, you 'd better use the original strings to represent them. Pattern elements (such as R'/t', are equivalent to '// t') Match corresponding special characters.

The following table lists the special elements in the regular expression mode syntax. If you provide optional flag parameters while using the mode, the meaning of some mode elements will change.

Of course, there are a lot of these usage methods, which will be frequently used in the future, and you will be able to understand them by trying more.

Mode

Mode Description
^ Match the start of a string
$ Matches the end of a string.
. Match any character. Except for line breaks, when the re. DOTALL mark is specified, it can match any character including line breaks.
[...] It is used to represent a group of characters and is listed separately: [amk] matches 'A', 'M', or 'K'
[^...] Character not in []: [^ abc] matches characters other than a, B, and c.
Re * Matches zero or multiple expressions.
Re + Matches one or more expressions.
Re? Matches 0 or 1 segment defined by the previous regular expression. It is not greedy.
Re {n}
Re {n ,} Exact match with n previous expressions.
Re {n, m} Match the segments defined by the regular expression n to m times. Greedy Mode
A | B Match a or B
(Re) G matches the expression in parentheses, which also represents a group
(? Imx) A regular expression contains three optional symbols: I, m, or x. Only the area in the brackets is affected.
(? -Imx) The regular expression disables the I, m, or x flag. Only the area in the brackets is affected.
(? : Re) Similar to (...), but does not represent a group
(? Imx: re) Use an I, m, or x flag in parentheses
(? -Imx: re) Do not use the I, m, or x optional flag in parentheses
(? #...) Note.
(? = Re) The forward positive identifier. If the regular expression is included in the regular expression, it indicates that the match is successful at the current position. Otherwise, the match fails. However, once the contained expression has been tried, the matching engine has not improved at all; the rest of the pattern also needs to try to the right of the separator.
(?! Re) A forward negative identifier. Opposite to the positive identifier. The expression contained in the string cannot match the current position of the string.
(?> Re) Matching independent mode, eliminating backtracking.
\ W Match letters and numbers
\ W Match non-alphanumeric characters
\ S Matches any blank character, which is equivalent to [\ t \ n \ r \ f].
\ S Match any non-empty characters
\ D Matching any number is equivalent to [0-9].
\ D Match any non-digit
\ Match string
\ Z Match string ends. If there is a line break, only the end string before the line break is matched. C
\ Z Match string ends
\ G The position where the last match is completed.
\ B Match A Word boundary, that is, the position between a word and a space. For example, 'er \ B 'can match 'er' in "never", but cannot match 'er 'in "verb '.
\ B Match non-word boundary. 'Er \ B 'can match 'er' in "verb", but cannot match 'er 'in "never '.
\ N, \ t, and so on. Match A linefeed. Match a tab. And so on
\ 1... \ 9 The child expression that matches the nth group.
\ 10 Match the child expression of the nth group if it matches. Otherwise, it refers to the expression of the octal verification code.

Character class

Instance Description
[Pp] ython Match "Python" or "python"
Rub [ye] Match "ruby" or "rube"
[Aeiou] Match any letter in 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 letter or number
[^ Aeiou] All characters except aeiou letters
[^ 0-9] Match characters other than numbers

Special character class

Instance Description
. Matches any single character except "\ n. To match any character including '\ n', use a pattern like' [. \ n.
\ D Match a numeric character. It is equivalent to [0-9].
\ D Match a non-numeric character. It is equivalent to [^ 0-9].
\ S Matches any blank characters, including spaces, tabs, and page breaks. It is equivalent to [\ f \ n \ r \ t \ v].
\ S Match any non-blank characters. It is equivalent to [^ \ f \ n \ r \ t \ v].
\ W Match any word characters that contain underscores. It is equivalent to '[A-Za-z0-9 _]'.
\ W Match any non-word characters. It is equivalent to '[^ A-Za-z0-9 _]'.

1.3re.match Function

Re. match tries to match a pattern from the starting position of the string. If the match is not successful, match () returns none.

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

Pattern Regular Expression

String matching string

Flags flag used to control the matching method.

Directly program:

Import string, rer = "abc" # Regular Expression if re. match (r, "abc"): # match print 'done' else: print 'defat'

Result:

Done

You can perform more exercises based on the usage of the above tables:

Import string, rer = "a. c" # regular expression. match any character. Except for line breaks, when the re. DOTALL mark is specified, it can match any character including line breaks. If re. match (r, "abc"): print re. match (r, "abc") print 'done' else: print 'defat'

Result:

<_ Sre. SRE_Match object at 0x01dd6158>

Done

Note that the matching successful string is not displayed here. re. match () returns an object and none if the matching succeeds.

We can use the group (num) or groups () matching object function to obtain the matching expression.

Matching object Method Description
Group (num = 0) The string that matches the entire expression. group () can input multiple group numbers at a time. In this case, it returns a tuples that contain the values of those groups.
Groups () Returns a tuple containing all group strings, from 1 to the group number contained.

Program:

 import string,re r = "a.c"  if re.match(r,"abc"):  line = re.match(r,"abc") print line.group() else: print 'defeat' 

Result:

Abc

1.3re.search Functions

Re. search () scans the entire string and returns the first successful match.

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

Pattern Regular Expression

String matching string

Flags flag used to control matching

Like re. match (), if the re. search Method matches successfully, a matching object is returned. Otherwise, None is returned.

Directly program:

import string,rer = "abc" s = 'aacawcabc'if re.search(r,s): line = re.search(r,s)print line.group() 

Result:

Abc

Note:

The difference between re. match () and re. search:

Re. match only matches the start of the string. If the start of the string does not conform to the regular expression, the match fails, and the function returns None; and re. search matches the entire string until a match is found.

1.4re.sub Function

The re. sub () function is used to replace matching items.

Re. sub (pattern, repl, string, max = 0)

Pattern Regular Expression

Repl replacement items

String matching string

The maximum number of times count is replaced. The default value is 0, indicating that all matches are replaced.

The returned string is replaced by a non-repeated match on the leftmost side of the RE in the string. If the mode is not found, the character is returned without changing.

Program:

import string,repattern = '\d' repl = "!" s = 'abcdefg' line = re.sub(pattern,repl,s)print line 

Result:

!!!!!!!!! Abcdefg

1.5 Regular Expression modifier-optional flag

Let's talk about what a flag is:

A regular expression can contain some optional identifier modifiers to control the matching mode. Modifier is specified as an optional flag. Multiple tags can be specified by bitwise OR (|. For example, re. I | re. M is set to I and M:

Modifier Description
Re. I Make matching case insensitive
Re. L Perform locale-aware matching
Re. M Multi-row matching, affecting ^ and $
Re. S Make. Match All characters including line breaks
Re. U Parses Characters Based on the Unicode Character Set. This flag affects \ w, \ W, \ B, \ B.
Re. X This flag gives you a more flexible format so that you can write regular expressions more easily.

Program:

import string,repattern = '[Aa][Bb][Cc][Dd]' s = 'AbCd' if re.match(pattern,s):line = re.match(pattern,s)print line.group() 

Result:

AbCd

The above program can be implemented by selecting a flag:

import string,repattern = 'abcd' s = 'AbCd' if re.match(pattern,s,re.I):line = re.match(pattern,s,re.I)print line.group() 

Result;

AbCd

1.6re.compile Function

The general procedure for using re is to use re first. the compile () function is used to compile the regular expression string form into a Pattern instance. Then, the Pattern instance is used to process text and obtain matching results (a Match instance). Finally, the Match instance is used to obtain information, perform other operations.

Program:

import string,repattern = re.compile('\d+') s = 'aabbccdd' if pattern.match(s):line = pattern.match(s)print line.group()

Result:

11223344

Articles you may be interested in:
  • More detailed Python Regular Expression operation guide (re)
  • Python Regular Expression overview and common characters
  • Python Chinese Regular Expression note
  • PYTHON Regular Expression re Module Instructions
  • The Python module learns the re regular expression.
  • Introduction to Python Regular Expressions
  • Common methods for the remodule of python Regular Expression
  • Examples of Regular Expression usage in Python
  • Python Regular Expression matches IP address instances
  • Regular Expressions in Python
  • Basic expression for writing python Crawlers
  • Python Regular Expression (Escape problem)
  • Python uses regular expressions to analyze and replace images on webpages
  • Example of python regular expression match and search usage
  • Python uses regular expressions to extract webpage URLs

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.