基于非贪婪的正则表达式替换javascript

时间:2016-04-28 14:08:43

标签: javascript regex

我想在javascript中使用非贪婪的正则表达式替换字符串,如:

"blank blank this is blank blank my blank channel for blank blank blank blank audio video transcription blank blank blank blank blank"

我正在寻找一种解决方案,可以全局替换多个blank连续出现的单blank。对于上面的字符串,结果应该是: blank this is blank my blank channel for blank audio video transcription blank

2 个答案:

答案 0 :(得分:1)

您不需要非贪婪的匹配。使用

/\bblank( blank)+\b/g

答案 1 :(得分:0)

描述

此正则表达式将执行以下操作:

  • 查找public static double[] createArray (int n, Scanner enter){ double[] tempArray = new double[n]; int pos=0; while (enter.hasNext()) { tempArray[pos++] = enter.nextDouble(); if (pos>=n) break; } return tempArray; } 后跟空格或字符串结尾的所有实例
  • 捕获多个连续实例

正则表达式:blank

替换为:(blank(?:\s+|$))+

解释

Regular expression visualization

$1

实施例

示例文字

NODE                     EXPLANATION
----------------------------------------------------------------------
  (                        group and capture to \1 (1 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    blank                    'blank'
----------------------------------------------------------------------
    (?:                      group, but do not capture:
----------------------------------------------------------------------
      \s+                      whitespace (\n, \r, \t, \f, and " ")
                               (1 or more times (matching the most
                               amount possible))
----------------------------------------------------------------------
     |                        OR
----------------------------------------------------------------------
      $                        before an optional \n, and the end of
                               a "line"
----------------------------------------------------------------------
    )                        end of grouping
----------------------------------------------------------------------
  )+                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------

搜索并更换后

blank blank this is blank blank my blank channel for blank blank blank blank audio video transcription blank blank blank blank blank

替代地

如果您希望用一个空格替换多个空格的所有实例,那么我只是使用:

正则表达式:blank this is blank my blank channel for blank audio video transcription blank

替换为:没有