【问题标题】:Match all text within two given markers匹配两个给定标记内的所有文本
【发布时间】:2016-05-10 14:07:30
【问题描述】:

假设我有两个自定义 javascript cmets。

开始://<!-,结束://!>

我想替换这些标记之间的所有内容,以及标记。

//<!- directiveDecoratorComment
    (function directiveDecorator() {
        if (typeof(angular) == 'undefined') return;
        var appElement = document.querySelector('[ng-app]');
        var appName = appElement.getAttribute('ng-app');
        if (typeof(appName) == 'undefined') return;
        var app = angular.module(appName);
        angular.forEach(app._invokeQueue, function(value, key) {
            if (value[1] == 'directive') {
                var directiveName = value[2][0];
                app.config(function($provide) {
                  $provide.decorator(directiveName + 'Directive', function($delegate) {
                    var directive = $delegate[0];
                    console.log("Decorating:",directiveName,'on',appName,'template now ==',"/views/" + directive.templateUrl);
                    directive.templateUrl = "/views/" + directive.templateUrl;
                    return $delegate;
                  });
                });
            }
        });
    }());

    //!>

所以这基本上会变成空字符串 javascript 文件。

这是我尝试过的。

string.replace(/([//<])(.+\n*?)([//!>])/g, '');

【问题讨论】:

标签: javascript regex replace


【解决方案1】:

你可以使用

/(\/\/<!-)([^\/]*(?:\/(?!\/!>)[^\/]*)*)(\/\/!>)/g

regex demo

正则表达式基于 unroll-the-loop 技术。

  • (\/\/&lt;!-) - 匹配并捕获文字 //&lt;!-
  • ([^\/]*(?:\/(?!\/!&gt;)[^\/]*)*) - 匹配并捕获除//!&gt; 之外的任何内容(此处展开循环意味着我们将除/ 之外的任何字符与[^\/]* 匹配,然后匹配零个或多个/ 组,而/!&gt; 和然后是任意数量的任意字符,但 /)
  • (\/\/!&gt;) - 匹配并捕获//!&gt;

请注意,如果您不使用捕获组,您可能会摆脱它们。

【讨论】:

    【解决方案2】:

    你想要的是这个:

    string.replace(/(\/\/\<\!\-)((.*\n)*.*)(\/\/\!\>)/, '')
    

    【讨论】:

    【解决方案3】:

    您可以使用非贪婪匹配来执行此操作而无需前瞻:

    /\/\/<!-[\s\S]*?\/\/!>/
     ^^^^^^^                    MATCH OPENING //<!-
            ^^^^^^^             ANYTHING IN BETWEEN
                   ^^^^^^^      CLOSING //!>
    

    \s\S 用于匹配换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2020-07-26
      • 2012-05-04
      相关资源
      最近更新 更多