Python Module Learning re

Source: Internet
Author: User

The methods used in the RE module are:

1, compile ()

Compiling a regular expression pattern is an object pattern, which can improve execution efficiency.

Grammar:

Re.compile (R ' pattern ', [flags])

where R means not escaping the string, which means \ t is .

For example:

Import Rehello = "hello,i am tom,nice to konw U." A = Re.compile (R ' to ') b = a.findall (hello) ["to", ' to ']

2. Match ()

The matching string must begin with pattern, otherwise it will not match.

Grammar:

Re.match (Pattern,string,[flags])

For example:

>>> a = "Hello" >>> b = Re.match (R ' L ', a) >>> b>>> C = re.match (R ' he ', a) >>> C&L T;_sre. Sre_match object; span= (0, 2), match= ' he ' >

3. Search ()

A match to the first pattern returns the result.

Grammar:

Re.search (Pattern,string,[flags])

For example:

>>> a = "Hellohe" >>> C = re.search (R ' he ', a). Group () >>> C ' he '

Note: The group () method is used to return a string because the search () method returns a Match object.

4, FindAll ()

Matches all of the pattern and returns a list.

Grammar:

Re.findall (Pattern,string,[flags])

For example:

>>> a = "Hello12kk32" >>> B = Re.findall (R ' \d+ ', a) >>> b[' 12 ', ' 32 ']

5, Sub ()

Match and replace.

Grammar:

Re.sub (Pattern,repl,string,count)

Example:

Import Retext = "Jgood is a handsome boy, he's cool, clever, and so on ..." Print (Re.sub (R ' \s+ ', '-', text)) execution results are as follows: Jgood-is -a-handsome-boy,-he-is-cool,-clever,-and-so-on ... The second parameter is the replaced string; In this case, the '-' fourth parameter refers to the number of replacements. The default is 0, which means that each match is replaced.

Python Module Learning re

Related Article

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.