您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中实现详细的REGEX

如何在Python中实现详细的REGEX

在定义正则表达式模式时使用原始字符串文字一个好习惯。许多正则表达式模式使用反斜杠,并且使用原始字符串文字将使您可以编写单个反斜杠,而不必担心Python是否会将您的反斜杠解释为具有不同的含义(在这种情况下,必须使用两个反斜杠) )。

\b?无效的正则表达式。这就是说0或1个字的边界。但是,要么您有单词边界,要么没有单词边界。如果您有单词边界,那么您就有1个单词边界。如果没有单词边界,那么您的单词边界为0。因此\b?(如果它是有效的正则表达式)将始终为真。

正则表达式区分字符串的结尾和行的结尾。(一个字符串可以包含多行。)

import re
verbose_item_pattern = re.compile(r"""
    $            # end of line boundary
    \s{1,2}      # 1-or-2 whitespace character, including the newline
    I            # a capital I
    [tT][eE][mM] # one character from each of the three sets this allows for unkNown case
    \s+          # 1-or-more whitespaces INCLUDING newline
    \d{1,2}      # 1-or-2 digits
    [.]?         # 0-or-1 literal .
    \(?          # 0-or-1 literal open paren
    [a-e]?       # 0-or-1 letter in the range a-e
    \)?          # 0-or-1 closing paren
    .*           # any number of unkNown characters so we can have words and punctuation
    [^0-9]       # anything but [0-9]
    $            # end of line boundary
    """, re.VERBOSE|re.MULTILINE)

x = verbose_item_pattern.search("""
 Item 1.0(a) foo bar
""")

print(x)

产量

<_sre.SRE_Match object at 0xb76dd020>

(表示匹配)

python 2022/1/1 18:44:50 有312人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶