zoukankan      html  css  js  c++  java
  • re正则表达式16_managing complex regexes

    Managing Complex Regexes

    Regular expressions are fine if the text pattern you need to match is simple. But matching complicated text patterns might require long, convoluted regular expressions. You can mitigate this by telling the re.compile() function to ignore whitespace and comments inside the regular expression string. This “verbose mode” can be enabled by passing the variable re.VERBOSE as the second argument tore.compile().

    Now instead of a hard-to-read regular expression like this:

    phoneRegex = re.compile(r'((d{3}|(d{3}))?(s|-|.)?d{3}(s|-|.)d{4}
    (s*(ext|x|ext.)s*d{2,5})?)')

    you can spread the regular expression over multiple lines with comments like this:

    phoneRegex = re.compile(r'''(
        (d{3}|(d{3}))?            # area code
        (s|-|.)?                    # separator
        d{3}                         # first 3 digits
        (s|-|.)                     # separator
        d{4}                         # last 4 digits
        (s*(ext|x|ext.)s*d{2,5})?  # extension
        )''', re.VERBOSE)

    Note how the previous example uses the triple-quote syntax (''') to create a multiline string so that you can spread the regular expression definition over many lines, making it much more legible.

    The comment rules inside the regular expression string are the same as regular Python code: The # symbol and everything after it to the end of the line are ignored. Also, the extra spaces inside the multiline string for the regular expression are not considered part of the text pattern to be matched. This lets you organize the regular expression so it’s easier to read.

     
  • 相关阅读:
    第三方库添加记录
    xcode之语法高亮效果消失解决办法
    将excel记录导入ms sql
    eWebEditor在IE8,IE7下所有按钮无效之解决办法
    关于对数据库中重复记录的操作
    javascript如何取得RadioButtonList的值
    水晶报表分页并自动插入空白行
    如何防止SQL注入
    VC++视频教程下载地址
    如何显示最近过生日的记录
  • 原文地址:https://www.cnblogs.com/webRobot/p/5224147.html
Copyright © 2011-2022 走看看