【问题标题】:Regular Expression for strings字符串的正则表达式
【发布时间】:2016-02-09 13:38:06
【问题描述】:

我希望在 Python 3 中为 lua 长字符串创建一个正则表达式。

它们应采用以下格式:

它们应该以“[”开头,然后是 0 个或多个“=”,然后是“[”。 之后应该是字符串,并以“]”结尾,然后是相同数量的等号和“]”。

例如:

[[ hello world ]]

[===[ hello world ]===]

[====[ trick ]==] still ]===] in the ]========] string ]====]

如果这很重要,我正在使用 python3

【问题讨论】:

  • 你在顶部说你想要一个 lua 正则表达式,然后在底部你说 Python。是哪个?
  • 我在用python写,但是[==[语法是lua语法。我将编辑我的问题以避免混淆
  • 如果他们在两边都需要相同数量的=,为什么最后一个示例只有一个(即不匹配的)八个?
  • 因为那不是字符串的结尾。它与“]====]”匹配
  • @TigerhawkT3 整行是有效匹配。它不会停在]=]

标签: python regex python-3.x lua


【解决方案1】:

我很确定这就是您要的:

\[(=*?)\[(.*?)\]\1\]

\[            #matches '[' literally
    (         #first capture group
        =*?   #match the smallest number of concurrent '=' signs to make this match valid
    )
\[            #matches '[' literally
    (         #second capture group (this is if you just want the string value)
        .*?   #matches the smallest number of characters to make this match valid
    )
\]            #matches ']' literally
    \1        #match an exact copy of the first capture group (makes sure both sides have the same number of equal signs)
\]            #matches ']' literally

Regex101

【讨论】:

  • 哇!你能解释一下吗?
  • @YahyaUddin 当然!我现在将编辑说明
  • 哇,我什至不知道 \1 的事情!
  • 等等这不一样:\[(=*)\[(.*?)\]\1\],因为下面的[是必需的
  • @YahyaUddin 是和否。这里的不同之处在于,通过使用*,您很容易进行更多的回溯,从而降低效率。如果您使用 *? 它不会回溯(假设有效的格式化字符串)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2013-12-15
  • 2016-01-24
相关资源
最近更新 更多