【问题标题】:regex match between two strings including those strings两个字符串之间的正则表达式匹配,包括那些字符串
【发布时间】:2014-02-04 14:49:03
【问题描述】:

示例字符串:

{{--
    some text
--}}

我正在尝试匹配 {{-- 直到并包括第一个 --}} 之间的任何内容 它还需要捕获返回和换行符。

我尝试过这样的事情:\{\{--[^\r\n]--\}\} 似乎捕获了括号之间的所有内容,但我不太清楚如何捕获括号。

编辑 我正在尝试修改一个崇高的文本插件,为 laravel 的刀片模板添加语法高亮。如下所述: '({{--[\s\S]*--}})' 匹配我想要匹配的内容。括号可能被不同的规则覆盖。

【问题讨论】:

  • 您的示例也匹配括号(括号在正则表达式中列出)。您在什么环境中执行此操作(您的正则表达式引擎和界面是什么)?您的示例很好,只是它不允许换行。如果我更了解您的环境以及您认为您的示例没有包含括号的原因,我可以帮助您解决这个问题。
  • 嗯。老实说,我不知道。基本上我在看一个 Sublime Text 2 的插件,它为 Laravel 的刀片模板添加了语法高亮。它的 cmets 不包含新行,所以我试图修复它,然后遇到了这个问题。仅适用于第一行的原件是:\{\{--(?=(|\s*|))(.+|)(?=(|--\}\}|)),如果有帮助的话。

标签: regex


【解决方案1】:

你可以使用这个正则表达式:

(\{\{--[\s\S]*--\}\})

在线演示:http://regex101.com/r/mT1jT4

说明:

1st Capturing group (\{\{--[\s\S]*--\}\})
\{ matches the character { literally
\{ matches the character { literally
-- matches the characters -- literally
[\s\S]* match a single character present in the list below
Quantifier: Between zero and unlimited times, as many times as possible,
            giving back as needed [greedy]
\s match any white space character [\r\n\t\f ]
\S match any non-white space character [^\r\n\t\f ]
-- matches the characters -- literally
\} matches the character } literally
\} matches the character } literally

【讨论】:

  • 这是一个甜蜜的网站!谢谢 - 这确实匹配正确......虽然在这种情况下它仍然没有达到我的预期。我的猜测是稍后会应用其他规则。不过,我仍然会将其标记为正确,因为这是按照我的要求进行的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多