jQuery Regex在两个括号之间获取字符串



我想在 [ch] and [/ch]

之间获取每个字符串
var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var testRE = test.match("[ch](.*)[/ch]"); alert(testRE[1]);

但是,我得到的结果是:

h]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/c

如何将每个字符串存储在数组中?我期望的结果是

chords = ["Bm","A","C"]

您当前模式的问题是次要但棘手的:

[ch](.*)[/ch]

.*数量将在[ch][/ch]之间尽可能多地消耗。这意味着您将始终在这里获得一场比赛:

Time flies by when[ch]A[/ch] the night is young

要获得每个匹配对,请使点懒惰,即使用(.*?)。考虑此代码:

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var regex = /[ch](.*?)[/ch]/g
var matches = [];
var match = regex.exec(test);
while (match != null) {
    matches.push(match[1]);
    match = regex.exec(test);
}
console.log(matches);

您可以使用此正则 /[ch](.*?)[/ch]/g

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var regex = /[ch](.*?)[/ch]/g;
var testRE = [];
var match;
while (match = regex.exec(test)) {
    testRE.push(match[1]);
}
console.log(testRE);

尝试splitfilter

test.split(/[ch]|[/ch]/).filter( (s,i ) => i % 2 == 1 )

演示

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var output = test.split(/[ch]|[/ch]/).filter((s, i) => i % 2 == 1);
console.log(output);

说明

  • Split[ch][/ch]
  • filter -in 甚至索引

最新更新