浅谈Python中re.match()和re.search()的使用及区别
作者:SpiderLiH 发布时间:2022-05-11 12:48:44
1.re.match()
re.match()的概念是从头匹配一个符合规则的字符串,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None。
包含的参数如下:
pattern: 正则模型
string : 要匹配的字符串
falgs : 匹配模式
match() 方法一旦匹配成功,就是一个match object对象,而match object对象有以下方法:
group() 返回被 RE 匹配的字符串
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span()返回一个元组包含匹配 (开始,结束) 的位置
案例:
import re
# re.match 返回一个Match Object 对象
# 对象提供了 group() 方法,来获取匹配的结果
result = re.match("hello","hello,world")
if result:
print(result.group())
else:
print("匹配失败!")
输出结果:
hello
2.re.search()
re.search()函数会在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
格式:re.search(pattern, string, flags=0)
要求:匹配出文章阅读的次数
import re
ret = re.search(r"\d+", "阅读次数为 9999")
print(ret.group())
输出结果:
9999
3.match()和search()的区别:
match()函数只检测RE是不是在string的开始位置匹配,
search()会扫描整个string查找匹配
match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
举例说明:
import re
print(re.match('super', 'superstition').span())
(0, 5)
print(re.match('super','insuperable'))
None
print(re.search('super','superstition').span())
(0, 5)
print(re.search('super','insuperable').span())
(2, 7)
补充知识: jupyter notebook_主函数文件如何调用类文件
使用jupyter notebook编写python程序,rw_visual.jpynb是写的主函数,random_walk.jpynb是类(如图)。在主函数中将类实例化后运行会报错,经网络查找解决了问题,缺少Ipynb_importer.py这样一个链接文件。
解决方法:
1、在同一路径下创建名为Ipynb_importer.py的文件:File-->download as-->Python(.py),该文件内容如下:
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import io, os,sys,types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell
class NotebookFinder(object):
"""Module finder that locates Jupyter Notebooks"""
def __init__(self):
self.loaders = {}
def find_module(self, fullname, path=None):
nb_path = find_notebook(fullname, path)
if not nb_path:
return
key = path
if path:
# lists aren't hashable
key = os.path.sep.join(path)
if key not in self.loaders:
self.loaders[key] = NotebookLoader(path)
return self.loaders[key]
def find_notebook(fullname, path=None):
"""find a notebook, given its fully qualified name and an optional path
This turns "foo.bar" into "foo/bar.ipynb"
and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
does not exist.
"""
name = fullname.rsplit('.', 1)[-1]
if not path:
path = ['']
for d in path:
nb_path = os.path.join(d, name + ".ipynb")
if os.path.isfile(nb_path):
return nb_path
# let import Notebook_Name find "Notebook Name.ipynb"
nb_path = nb_path.replace("_", " ")
if os.path.isfile(nb_path):
return nb_path
class NotebookLoader(object):
"""Module Loader for Jupyter Notebooks"""
def __init__(self, path=None):
self.shell = InteractiveShell.instance()
self.path = path
def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)
print ("importing Jupyter notebook from %s" % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4)
# create the module and add it to sys.modules
# if name in sys.modules:
# return sys.modules[name]
mod = types.ModuleType(fullname)
mod.__file__ = path
mod.__loader__ = self
mod.__dict__['get_ipython'] = get_ipython
sys.modules[fullname] = mod
# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__
try:
for cell in nb.cells:
if cell.cell_type == 'code':
# transform the input to executable Python
code = self.shell.input_transformer_manager.transform_cell(cell.source)
# run the code in themodule
exec(code, mod.__dict__)
finally:
self.shell.user_ns = save_user_ns
return mod
sys.meta_path.append(NotebookFinder())
2、在主函数中import Ipynb_importer
import matplotlib.pyplot as plt
import Ipynb_importer
from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
3、运行主函数,调用成功
ps:random_walk.jpynb文件内容如下:
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
x_step = x_direction * x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
运行结果:
来源:https://blog.csdn.net/weixin_38819889/article/details/93846579
猜你喜欢
- 一、基本(1)利用pytorch建好的层进行搭建import torchfrom torch import nnfrom torch.nn
- 最近工作需要用到序列匹配,检测相似性,不过有点复杂的是输入长度是不固定的,举例为:input_and_output = [1, 2,
- 本文在前面文章基础上介绍tkinter添加图片和文本,在这之前,我们需要安装一个图片库,叫Pillow,这个需要下载exe文件,根据下面图片
- 很早以前就说过,IE8的标准模式已经不再支持滤镜了,不过IE仍然留了一条后路,你可以在CSS中这样写滤镜:-ms-filter
- 在mysql中利用select语句的一个特性就可以很方便地实现查询结果的分页,select语句的语法:SELECT [STRAIGHT_JO
- javascript过滤数组重复元素的实现方法 以下是在
- 根据"客服果果"的"十几行的超简日历组件"http://bbs.51js.com/viewthrea
- eval函数就是实现list、dict、tuple与str之间的转化str函数把list,dict,tuple转为为字符串一、字符串转换成列
- 本文为大家分享了python实现图书馆研习室自动预约的具体代码,供大家参考,具体内容如下简介现在好多学校为学生提供了非常良好的学习环境,通常
- 解包在英文里叫做 Unpacking,就是将容器里面的元素逐个取出来放在其它地方,好比你父母去菜市场买了一袋苹果回来分别发给家里的每个成员,
- 如何阻止别人非法链接你网站的图片,防盗链?getimage.asp<% Option ExplicitDim&nb
- Case:需要给一个现有的shp数据创建一个字段,并将属性表中原有的一个文本类型的属性转换为整型后填入新创建的字段。Problem:新字段创
- CSS圆角的现实一直是大家所热衷的话题,我们进行CSS布局一直强调语义,强调文档的结构。圆角作为页面的外面表现,应该分离到CSS文件中,可以
- 在pycharm中我们有时需要切换python的版本,这里需要注意的是我们是在PyCharm中的Preferences中切换的,在File的
- 使用微信获取地址信息是和微信支付一道申请的,微信支付申请通过,就可以使用该功能。微信商城中,使用微信支付获取用户的收货地址,可以省略用户输入
- 使用Python 2.7 + pywin32 + wxpython开发每隔一段时间检测一下服务是否停止,如果停止尝试启动服务。进行服务停止日
- 本文实例为大家分享了Python基于OpenCV实现人脸检测,并保存的具体代码,供大家参考,具体内容如下安装opencv如果安装了pip的话
- 创建用户定义函数,它是返回值的已保存的 Transact-SQL 例程。用户定义函数不能用于执行一组修改全局数据库状态的操作。与系统函数一样
- 一、subprocess以及常用的封装函数运行python的时候,我们都是在创建并运行一个进程。像Linux进程那样,一个进程可以fork一
- 在Flash播放器运行时,将不同来源的资源划分到独立的沙箱(sandbox)内,不同沙箱之间不能彼此操作数据(除非目标沙箱做过一些设置,授权