Python 中的匹配与搜索

pythonserver side programmingprogramming更新于 2025/4/25 18:52:17

Python 提供了两种基于正则表达式的不同原始操作:ma​​tch 仅在字符串开头检查匹配,而 search 检查字符串中任意位置的匹配(这是 Perl 默认执行的操作)。

示例

#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print "match --> matchObj.group() : ", matchObj.group()
else:
   print "No match!!"
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
   print "search --> searchObj.group() : ", searchObj.group()
else:
   print "Nothing found!!"

输出

执行上述代码时,会产生以下结果 −

无匹配!!
search --> searchObj.group() : dogs

相关文章


有用资源