网络编程
位置:首页>> 网络编程>> Python编程>> python利用正则表达式搜索单词示例代码

python利用正则表达式搜索单词示例代码

作者:caimouse  发布时间:2023-02-21 11:31:03 

标签:python,正则表达式,搜索单词

前言

在python中,通过内嵌集成re模块,程序媛们可以直接调用来实现正则匹配。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。

比如下面的例子,就是用来从一段文字里查找一个单词,如下:

示例代码


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]))

结果输出如下:


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

在这里使用start()表示匹配的开始位置,end()表示结束位置。

来源:http://blog.csdn.net/caimouse/article/details/78069953

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com