【问题标题】:Removing extra whitespace at end of RegExp?在 RegExp 末尾删除多余的空格?
【发布时间】:2016-01-13 08:42:17
【问题描述】:

我正在使用此代码来缩进一段文本。它工作正常,但它在末尾添加了空白。

public var indentPattern:RegExp = /([\t ]*)(.*)$/gm;
public function indent(input:String, indentAmount:String = "\t"):String {
    if (input==null || input=="") return indentAmount;

    var indentedText:String = input.replace(indentPattern, indentAmount + "$1$2");
    return indentedText;
}

测试输入数据:

<style type="text/css">
    html, body {
        height:100%;
        margin:0;
        padding:0;
        line-height:.8;
    }

    *, *:before, *:after {
        -moz-box-sizing:border-box;
        -webkit-box-sizing:border-box;
        box-sizing:border-box;
    }

</style>

实际输出:

    <style type="text/css">     
    html, body {        
        height:100%;        
        margin:0;       
        padding:0;      
        line-height:.8;     
    }       

    *, *:before, *:after {      
        -moz-box-sizing:border-box;     
        -webkit-box-sizing:border-box;      
        box-sizing:border-box;      
    }       



    </style>        

注意:当我说末尾的空格时,制表符是在分号后的行尾添加的。尝试突出显示页面上的文本以查看我在说什么。

【问题讨论】:

    标签: javascript regex actionscript-3


    【解决方案1】:

    问题是

    ([\t ]*)(.*)$
    

    可以匹配一个空字符串。因此,在行尾匹配一个空字符串,并将indentAmount 放置在那里。将其更改为:

    ([\t ]*)(.+)$
    

    See it in action

    或者让匹配从每一行的开头开始:

    ^([\t ]*)(.*)$
    

    See it in action

    【讨论】:

      【解决方案2】:

      如果其他一切都到位,请在返回之前尝试删除它们:

      indentedText = indentedText.replace(/\s+$/g, '');
      

      【讨论】:

      • 我认为这里更合适的正则表达式是indentedText = indentedText.replace(/[ \t]+$/gm, '');
      猜你喜欢
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多