Home >Backend Development >Python Tutorial >Python uses regular expressions to implement sample code for searching words

Python uses regular expressions to implement sample code for searching words

黄舟
黄舟Original
2017-09-25 11:26:551814browse

Regular expression itself is a small, highly specialized programming language. The following article mainly introduces you to the relevant information about using regular expressions to search for words in Python. The article gives detailed example code. , friends in need can refer to it, let’s take a look below.

Preface

In python, through the embedded re module, programmers can directly call it to achieve regular matching. Regular expression patterns are compiled into a series of bytecodes and then executed by a matching engine written in C.

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

Example code


import re 
 
pattern = 'this' 
text = 'http://blog.csdn.net/caimouse is 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 result output is as follows:


##

Found "this"
in "http://blog.csdn.net/caimouse is great, this is great way!"
from 40 to 44 ("this")

Use

start( here ) indicates the starting position of matching, and end() indicates the ending position.

Summarize

The above is the detailed content of Python uses regular expressions to implement sample code for searching words. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn