Python Regular Expressions

Source: Internet
Author: User

RE module operation

When you need to match a string in Python with a regular expression, you can use a module with the name re

1. Re-module use process
    #coding=utf-8    # 导入re模块    import re    # 使用match方法进行匹配操作    result = re.match(正则表达式,要匹配的字符串)    # 如果上一步匹配到数据的话,可以使用group方法来提取数据 result.group()
Re.match is the method used to perform a regular match check, and if the string matches a regular expression, the match method returns the matching object (Match object), otherwise none (note is not an empty string ""). The Macth object has a group method that returns a matching portion of the string.

Single-character matching for regular expressions

character function
. Matches any of 1 characters (except \ n)
[ ] Match the characters enumerated in []
\d Match number, which is 0-9
\d Matches a non-numeric, that is, not a number
\s Match whitespace, that is, the Space, TAB key
\s Match non-whitespace
\w Match word characters, i.e. A-Z, A-Z, 0-9, _
\w Match non-word characters
2. Original string

Description

Python中字符串前面加上 r 表示原生字符串

As with most programming languages, 正则表达式里使用"\"作为转义字符 this can cause a backslash to haunt. If you need to match the character "\" in the text, you will need 4 backslashes "\ \" 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, with the original string, you no longer have to worry about missing the backslash, and the expression is more intuitive to write.

Represents quantity

Match related formats for multiple characters

character function
* Matches the previous character 0 or more times, which is optional
+ Match the previous character 1 or more times, i.e. at least 1 times
? Matches the previous character 1 or 0 times, either 1 times or no
{m} Match the previous character appears m times
{m,} Matches the previous character at least m times
{M,n} Match the previous character appears from M to N times
Represents a boundary
character function
^ Match string start
$ Match string End
\b Match the boundaries of a word
\b Match non-word boundaries
Match grouping
character function
| Match one or both of the expressions
(AB) Grouping characters in parentheses as a group
\num String that references the grouping num matches to
(?P<name>) Group up aliases
(? P=name) String to which the reference alias matches the name group
Advanced usage of the RE module search

Requirements: Matches the number of articles read

#coding=utf-8import reret = re.search(r"\d+", "阅读次数为 9999")ret.group()

FindAll

Requirements: Statistics of Python, C, C + + corresponding articles read the number of times

#coding=utf-8import reret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")print ret

Sub replaces the matched data

Requirements: Match to the number of reads plus 1

Method 1:

#coding=utf-8import reret = re.sub(r"\d+", ‘998‘, "python = 997")print ret

Method 2:

#coding=utf-8import redef add(temp):    strNum = temp.group()    num = int(strNum) + 1    return str(num)ret = re.sub(r"\d+", add, "python = 997")print retret = re.sub(r"\d+", add, "python = 99")print ret

Split cuts the string based on the match and returns a list

Requirement: Cut string "Info:xiaozhang Shandong"

#coding=utf-8import reret = re.split(r":| ","info:xiaoZhang 33 shandong")print ret

Python greedy and non-greedy

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;

Non-greedy is the opposite, always trying to match as few characters as possible.

Add after "*", "?", "+", "{m,n}"? , so that greed becomes non-greedy.

>>> s="This is a number 234-235-22-423">>> r=re.match(".+(\d+-\d+-\d+-\d+)",s)>>> r.group(1)‘4-235-22-423‘>>> r=re.match(".+?(\d+-\d+-\d+-\d+)",s)>>> r.group(1)‘234-235-22-423‘>>>

The regular expression pattern is used in a wildcard word, when it evaluates from left to right, it tries to "crawl" to match the longest string, in the example above, ". +" fetches the longest character of the pattern from the beginning of the string, including most of the first integer field we want, "\d+ "Only one character can match, so it matches the number" 4 ", and". + "matches all characters from the beginning of the string to the first digit 4.

Workaround: Non-greedy operator "? ", this operator can be used in" * "," + ","? " , the less a regular match is required, the better.

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.