Python 中的 match 函数
pythonserver side programmingprogramming更新于 2025/4/25 17:16:17
此函数尝试使用可选标志将 RE 模式与字符串进行匹配。
语法
以下是此函数的语法 −
re.match(pattern, string, flags=0)
以下是参数 − 的描述
| Sr.No. | 参数 &描述 |
|---|---|
| 1 | 模式 这是要匹配的正则表达式。 |
| 2 | 字符串 这是字符串,将搜索该字符串以匹配字符串开头的模式。 |
| 3 | 标志 您可以使用按位或 (|) 指定不同的标志。这些是修饰符,列在下表中。 |
re.match 函数在成功时返回 match 对象,在失败时返回 None。我们使用match对象的group(num)或groups()函数来获取匹配的表达式。
| Sr.No. | Match 对象方法与说明 |
|---|---|
| 1 | group(num=0) 此方法返回整个匹配(或特定子组编号) |
| 2 | groups() 此方法以元组形式返回所有匹配的子组(如果没有则为空) |
示例
#!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!"
输出
执行上述代码时,会产生以下结果 −
matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

