jquery正则表达式获取两个括号之间的字符串

时间:2018-02-21 09:42:59

标签: javascript 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"]

3 个答案:

答案 0 :(得分:2)

您当前模式的问题很小但很棘手:

\[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);

答案 1 :(得分:1)

您可以使用此正则表达式/\[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);

答案 2 :(得分:0)

尝试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);

<强>解释

    {li> Split [ch][/ch]
  • filter - 在偶数索引