【问题标题】:Python Regular Expression to match specific sequence of charactersPython正则表达式匹配特定的字符序列
【发布时间】:2015-01-15 07:36:15
【问题描述】:

我是 Python 中正则表达式的一个非常基本的用户,需要一些专家建议 解决一个使用正则表达式的问题。

我正在尝试使用以下规则从字符串中提取一些信息。

  1. $( 开头
  2. 开始标签后必须有一个词。
  3. 可选,后面可能包含的单词
    • '" 以外的任何字符 [如果单独使用而不成对使用] 直到结束字符 )
    • '" [如果单独使用而不成对使用] 仅在使用 \
    • 甚至可以允许 ) 如果包含在 ''"" 中。
  4. ) 结尾

作为一种解决方案,如果允许以某种方式在字符集 [] 中定义和使用特殊类型的字符,那将很容易。

例如:

re.compile("""\$\((\w*)
              [(any characters except ' and " [if used singly not in pairs] )
               (' and " [if used singly not in pairs] are allowed only if escaped using a \)
               ( even ) if enclosed within '' or "")
              ]\)""", re.VERBOSE)

一些测试:

  • this $(listInput) tail -> listInput
  • 这个 $(listInput:DS) 尾部 -> listInput:DS
  • 这个 $(listInput:J=") ":S=.o) 尾巴 -> listInput:J=") ":S=.o
  • this $(listInput:J=join\'with) tail -> listInput:J=join'with

是否可以在 Python 中做这样的事情,或者我对解决方案的方法不是 Pythonic ? 还建议,如果有更好的解决方案。

谢谢

【问题讨论】:

    标签: python regex python-2.6


    【解决方案1】:

    这个似乎按照你的要求做:

    ^\$\((\w(?:\w|[^)\\"']|"[^"]*"|'[^']*'|\\"|\\')*)\)
    

    分解:

    ^                   # start of string
    \$\(                # "$("
    (                   # start group 1
      \w                  # a word character
      (?:                 # start non-capturing group, one of:
        \w                  # a word character
        |                   # or
        [^)\\"']            # anything except ")" and special characters
        |                   # or
        "[^"]*"             # a double-quoted section
        |                   # or
        '[^']*'             # a single-quoted section
        |                   # or
        \\"                 # a backslash-escaped double quote
        |                   # or 
        \\'                 # a backslash-escaped single quote
      )*                  # end group, repeat
    )                   # end group 1
    \)                  # ")"
    

    它与您的示例所需的匹配。

    缺点:

    • 在没有更好的“单词”规范的情况下,我使用了\w。熟悉 \w 匹配的内容,并在必要时使用更具体的内容。
    • 不允许引用嵌套。 (这是 Python 正则表达式无法做到的)
    • 它在引用部分的结束引号上运行。需要更多信息才能做到这一点。
    • 引用部分中没有转义引号(尽管可以添加)

    测试:

    regex = re.compile("^\$\((\w(?:\w|[^)\\\"']|\"[^\"]*\"|'[^']*'|\\\"|\\')*)\)")
    string = "$(listInput:J=join\'with) tail"
    
    r = regex.search(string)
    
    r.groups()
    # -> (u"listInput:J=join\\'with",)
    
    regex.findall(string)
    # -> [u"listInput:J=join\\'with"]
    

    【讨论】:

    • 感谢@Tomalak,您的解决方案对我的帮助完全符合我的预期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多