Skip to main content
 首页 » 编程设计

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

2025年05月04日23mayingbao

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

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

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

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

例如:

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) 尾部 -> listInput:J=") ":S=.o
  • 这个 $(listInput:J=join\'with) 尾部 -> listInput:J=join'with

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

谢谢

请您参考如下方法:

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

^\$\((\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"]