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

Javascript regex between string delimiters

我有以下字符串:

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

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

我的正则表达式:/%([\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();
} );

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

我的 FIDDLE

我需要什么:

我想遍历匹配项

%||1234567890||乔||%

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

做点什么

您需要在 String#replace 中使用回调并修改模式以仅匹配 %||||% 中的内容,如下所示:

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 模式将匹配:

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

因为他尽量多拿,而[\s\S]基本上就是"anything"。所以他什么都拿。

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