Python uses regular expressions to implement sample code to search for words

Source: Internet
Author: User
The regular expression itself is a small, highly specialized programming language, the following article is mainly about Python using regular expressions to implement search words related data, the text gives a detailed example code, the need for friends can refer to, the following to see together.

Objective

In Python, Cheng can be called directly to implement a regular match by embedding the RE module inline. The regular expression pattern is compiled into a sequence of bytecode, which is then executed by a matching engine written in C.

For example, the following is used to find a word from a text, as follows:

Sample code


Import re  pattern = ' this ' text = ' http://blog.csdn.net/caimouse are great, this is great way! '  Match = Re.search (pattern, text)  s = Match.start () e = Match.end ()  print (' Found ' {} ' \nin ' {} ' \nfrom {} to {} ("{}" ) '. Format (  Match.re.pattern, match.string, S, E, text[s:e]))

The resulting output is as follows:


Found "This" in "Http://blog.csdn.net/caimouse are great, this is great way!" From-to-("this")

Here you use the start() start position that represents the match, and End () indicates the end position.

Summarize

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.