字符串分隔符之间的Javascript正则表达式

时间:2017-03-31 09:03:19

标签: javascript regex regex-greedy

我有以下字符串:

%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%

问题:我正在尝试匹配%|| .... ||%之间的所有匹配项并处理这些子字符串匹配

MY REGEX:/%([\s\S]*?)(?=%)/g

我的代码

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );

现在模式似乎正在选择%||的第一次和最后一次出现之间的所有内容....%||

MY FIDDLE

我需要什么:

我想迭代匹配

%|| || 1234567890乔||%

%|| || 1234567890罗伯特||%

并做点什么

2 个答案:

答案 0 :(得分:1)

您需要在<script id = "myScript" type="text/template"> <% _.each(data, function(res){}); %> </script> 中使用回调并修改模式,使其仅匹配String#replace%||内的内容,如下所示:

&#13;
&#13;
||%
&#13;
&#13;
&#13;

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%"; var pattern = /%\|\|([\s\S]*?)\|\|%/g; a = a.replace( pattern, function (match, group1){ var chunks = group1.split('||'); return "{1}" + chunks.join("-") + "{/1}"; } ); console.log(a);模式将匹配:

  • /%\|\|([\s\S]*?)\|\|%/g - %\|\|子字符串
  • %|| - 捕获第1组匹配任何0+字符,尽可能少到第一个...
  • ([\s\S]*?) - \|\|%子字符串
  • ||% - 多次。

答案 1 :(得分:0)

因为他尽可能多地尝试,[\ s \ S]基本上意味着“任何事情”。所以他拿走了任何东西。

RegExp parts without escaping, exploded for readability
start tag : %||
first info: ([^|]*) // will stop at the first |
separator : ||
last info : ([^|]*) // will stop at the first |
end tag   : ||%

Escaped RegExp:
/%\|\|([^\|]*)\|\|([^\|]*)\|\|%/g