2007年1月31日星期三

在Python中使用正则表达式

Python 的HowTo 文档Regular Expression HOWTO是学习Python 正则表达式的最佳参考. 现在还没有中文版. 有时间我希望能把它翻译成中文版. 这篇文档在Python的自带文档中也有.
这里是几个我看文档的新得:

  • 1. match 和 search的区别. match从string的开始匹配, 而search从任何位置匹配. 虽然用match(r'.*word')可以代替search(r'word'), 但因为.*阻止了优化, 所以除非从开始匹配, 其他情况推荐用search.

  • 2.怎样匹配一个完整的word, 用 re.search(r'\bword\b', 'this is a word , this is not a words'), 注意要有r, 否则\b将当作ASCII值为8的字符, 当然也可以这样, re.search('\\bword\\b', ...).

  • 3.多行匹配问题, 一般情况下, ^和$代表字符串的唯一的开始和结束位置, 当设置re.MULTILINE标志时, ^和$代表每行的开始和结束.

  • 4.re.DOTALL标志指示'.'可以代表newline.

  • 5.Lookahead Assertsion是很有用的模式,比如: .*[.](?!bat$exe$).*$ 可以匹配所有不以.exe和.bat结尾的带扩展的文件名. (?!...)代表当前位置不出现...

  • 6.非贪婪匹配, .* 是贪婪匹配, .*?, 非贪婪,



  • 这是Regular Expression HOWTO所有的章节:
    Contents
    1 Introduction
    2 Simple Patterns
    2.1 Matching Characters
    2.2 Repeating Things
    3 Using Regular Expressions
    3.1 Compiling Regular Expressions
    3.2 The Backslash Plague
    3.3 Performing Matches
    3.4 Module-Level Functions
    3.5 Compilation Flags
    4 More Pattern Power
    4.1 More Metacharacters
    4.2 Grouping
    4.3 Non-capturing and Named Groups
    4.4 Lookahead Assertions
    5 Modifying Strings
    5.1 Splitting Strings
    5.2 Search and Replace
    6 Common Problems
    6.1 Use String Methods
    6.2 match() versus search()
    6.3 Greedy versus Non-Greedy
    6.4 Not Using re.VERBOSE
    7 Feedback
    About this document ...