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")
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!