Python正则表达式匹配特定的字符序列

时间:2014-11-18 07:27:32

标签: python regex python-2.6

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

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

  1. $(
  2. 开头)开头
  3. 开始标记后必须有一个单词。
  4. (可选),可能包含以下字词
    • ' [,如果单独使用,不成对]之外的任何字符,直到结束字符
    • 只有在使用 \ 进行转义时,才允许
    • ' [如果单独使用,不成对]
    • 如果包含在''“”中,
    • 甚至可以允许
  5. 结尾
  6. 结束

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

    例如:

    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)
    

    一些测试:

    • 这个$(listInput)尾 - > listInput
    • 此$(listInput:DS)尾 - > listInput:DS
    • 此$(listInput:J =“)”:S = .o)tail - > listInput:J =“)”:S = .o
    • 这个$(listInput:J = join \'with)tail - > listInput:J = join'with

    是否可以在Python中执行此类操作,或者我对解决方案的处理方法不是Pythonic? 还建议,如果有更好的解决方案。

    感谢

1 个答案:

答案 0 :(得分: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"]