Python's Archiver

為方便港臺同胞閱覽,Python中國特別推出簡繁體內容轉換功能

zkfarmer 发表于 2008-11-10 14:07

4.2.2 匹配vs查找

Python提供两种不同的基于正则表达式的原始操作:匹配和查找。如果你是习惯于Perl的语义,search操作是你要找的内容。参见search()函数和编译的正则表达式对象对应的方法。

注意匹配不同于使用以”^”开始的正则表达式的查找:”^”仅在字符串开始处匹配,或在多行模式中立即换行。只在模式匹配在不考虑模式的字符串开始时,或由可选的pos参数给定的不考虑是否在它之前有一个换行的开始位置时,”match”操作才能成功。

re.compile("a").match("ba", 1)           # succeeds
re.compile("^a").search("ba", 1)         # fails; 'a' not at start
re.compile("^a").search("\na", 1)        # fails; 'a' not at start
re.compile("^a", re.M).search("\na", 1)  # succeeds
re.compile("^a", re.M).search("ba", 1)   # fails; no preceding \n

出处[url=http://www.okpython.com]Python中国[/url],由zkfarmer翻译整理,提交错误和在建议在[url=http://www.zkfarmer.org]这里[/url]。

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.