正则表达式查找2个动态字符串之间的内容

时间:2018-03-22 22:39:19

标签: javascript regex gulp

我目前正在开发一个gulp插件,可以找到类似[! @if (this) !][! @endif !]的语法,但这是动态的,if总是会改变。

我希望能够做一些正则表达式,我将能够在文件的内容中搜索if语句并获取中间的内容,以便我可以选择是否删除基于内容的内容在使用命令gulp --statements false传递的标志上,不允许语句显示在其中的实际内容,因为这对于开发目的无关紧要。

所以我可以拥有这样的代码......

This is just some dummy data that will not get removed.

[! @if (this_is_some_var) !]
   I would be able to get this text!
[! @endif !]

This is some more dummy data that will not get removed.

[! @if (this_is_another_var) !]
    And this text!
[! @endif !]

基本上我希望Javascript / RegEx能够返回以下I would be able to get this text!,然后使用Javascript删除或保留该内容,具体取决于传入的参数。

3 个答案:

答案 0 :(得分:0)

这可能是您可以使用的起点。

\[\!(?!\!\]).+\!\]\s((?!\[\!).+)\s\[\!(?!\!\]).+\!\]

https://regex101.com/r/kz6K6i/1

答案 1 :(得分:0)

You could use this one

/(?:^\[!\s@if\s\(.*\)\s!\])\s+(.*)\s+(?:\[!\s@endif\s!\]$)/gium;

demo & regex playground

答案 2 :(得分:0)

这可能适合您的情况

\[! @if \((.*)\) !\]\s+(.*)(?=\s+\[! @endif !\])

Demo

  • 捕获1:每个If语句变量
  • 捕获2:内容字符串到If语句