【问题标题】:Python regex - Find multiple characters in a substringPython regex - 在子字符串中查找多个字符
【发布时间】:2017-09-18 08:05:27
【问题描述】:
print 'cycle' ;While i in range(1,n) [[print "Number:" ;print i; print 'and,']]

例如,我有这样的一行。我只想从双方括号内的 [[ ... ]] 子字符串中提取分号字符。

如果我使用re.search(\[\[.*(\s*;).*\]\]),我只会得到一个分号。有没有合适的解决方案?

【问题讨论】:

  • 不,没有真正好的正则表达式解决方案,但;(?=(?:(?!\[\[).)*\]\]) 可能工作得很好。
  • 您能否简要解释一下这是如何工作的?
  • 与其使用正则表达式来尝试匹配 [[ ]] 内的每个分号分隔的组,您可能会发现使用正则表达式提取 [[ ]] 内的所有内容,然后拆分它更容易、更健壮在分号上捕获。这将避免不应该匹配的已接受解决方案的问题!

标签: python regex python-2.7 regex-group


【解决方案1】:

正则表达式从来都不是这样的好选择,因为它很容易出错,但以下模式适用于琐碎的情况

;(?=(?:(?!\[\[).)*\]\])

模式分解:

;                # match literal ";"
(?=              # lookahead assertion: assert the following pattern matches:
    (?:          
        (?!\[\[) # as long as we don't find a "[["...
        .        # ...consume the next character
    )*           # ...as often as necessary
    \]\]         # until we find "]]"
)

换句话说,该模式检查分号后是否跟]],但后面是否跟[[


模式不起作用的字符串示例:

  • ; ]](将匹配)
  • [[ ; "this is text [[" ]](不匹配)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多