python--pattern中的match、search方法

1.match

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

这个方法将从string的pos下标处起尝试匹配pattern。

注意:这个方法并不是完全匹配。

当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'。

# encoding: UTF-8
import re
 
# 将正则表达式编译成Pattern对象
pattern1 = re.compile(r'hello') #完全匹配
pattern2 = re.compile(r'hello%') #不完全匹配
 
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match1 = pattern1.match('hello world')
match2 = pattern2.match('hello world')
 
if match1:
    print match1.group()
else:
    print 'match1 failed'

if match2:
    print match2.group()
else:
    print 'match2 failed'
 
### 输出 ###
# hello
# match2 failed

2.search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
这个方法用于查找字符串中可以匹配成功的子串。

从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));

1.match()函数只检测re是不是在string的开始位置匹配,即只在position为0时开始;

2.search()会扫描整个string查找匹配

# -*- coding: utf-8 -*-
# 一个简单的search实例
import re
 
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'world')
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()无法成功匹配
match1 = pattern.search('hello world!')
match2 = pattern.match('hello world!')
 
if match1:
    # 使用Match获得分组信息
    print match1.group()
else:
    print 'failed 1'
if match2:
    print match2.group()
else:
    print 'failed 2'
 
### 输出 ###
# world
# failed 2

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonmatch是一个用于模式匹配的关键字。它可用于匹配和提取字符串或其他数据类型的特定模式。 在使用match之前,我们需要导入re模块(正则表达式模块),以便使用其提供的功能。 使用match时,我们可以使用正则表达式来指定要匹配的模式。下面是一个简单的例子: ```python import re string = "Hello, World!" pattern = r"Hello" result = re.match(pattern, string) if result: print("匹配成功") else: print("匹配失败") ``` 在上面的例子,我们使用re模块的match函数来匹配字符串的模式。我们使用r"Hello"作为正则表达式模式,它表示匹配字符串的"Hello"。然后,我们将结果赋给result变量。 如果匹配成功,则match函数返回一个匹配对象;否则返回None。在上面的例子,由于字符串的"Hello"与模式匹配,所以结果为匹配成功。 我们可以使用匹配对象的group()方法来获取匹配的内容: ```python import re string = "Hello, World!" pattern = r"Hello" result = re.match(pattern, string) if result: print("匹配成功") print("匹配的内容为:", result.group()) else: print("匹配失败") ``` 在上面的例子,我们使用group()方法获取匹配的内容。因为我们只有一个匹配项,所以输出为"Hello"。 除了字符串,我们还可以在其他数据类型使用match进行模式匹配。但是需要注意,match在匹配时是从字符串的开头开始匹配的。如果我们希望从字符串的任意位置开始匹配,可以使用search函数。 总之,matchPython用于模式匹配的关键字。我们可以使用正则表达式来定义要匹配的模式,并使用re模块的match函数来进行模式匹配操作。如果匹配成功,我们可以使用匹配对象的group()方法来获取匹配的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值