Javascript Regex multiline无法正常工作

时间:2014-03-07 17:53:17

标签: javascript regex multiline

鉴于代码:

var regExGroup = new RegExp("\\[group(.*)\\][\s\S]*\\[/group]", 'gi');
var regExResGroup;
while ((regExResGroup = regExGroup.exec(result)) !== null) {
    console.log(regExResGroup[0]);
}

测试数据(result的值):

[comment]This is a comment[/comment][group title="This" description="That"]
[comment]This is a comment[/comment]
[event]
[condition object="Touch"]On touch[/condition]
[condition object="Touch"]On touch[/condition]
[action object="Sprite"]Destroy[/action]
[action object="Sprite"]Destroy[/action]
[comment]This is a comment[/comment]
[event]
[condition object="Touch"]On touch[/condition]
[condition object="Touch"]On touch[/condition]
[action object="Sprite"]Destroy[/action]
[action object="Sprite"]Destroy[/action]
[/event]
[/event]
[group title="This" description="That"]
[event]
[condition object="Touch"]On touch[/condition]
[condition object="Touch"]On touch[/condition]
[action object="Sprite"]Destroy[/action]
[action object="Sprite"]Destroy[/action]
[event]
[condition object="Touch"]On touch[/condition]
[condition object="Touch"]On touch[/condition]
[action object="Sprite"]Destroy[/action]
[action object="Sprite"]Destroy[/action]
[/event]
[/event]
[/group]
[/group]

为什么找不到匹配项?

2 个答案:

答案 0 :(得分:0)

多行是m,而不是gg用于全局,以匹配正则表达式的所有实例。否则只会匹配一次

new RegExp("\\[group(.*)\\][\s\S]*\\[/group]", 'gim');

答案 1 :(得分:0)

我猜你可以试试其中一个引用/分隔符选项

 #  (?s)\[group(.*?)\].*?\[/group\]
 # /(?s)\[group(.*?)\].*?\[\/group\]/
 # '/(?s)\[group(.*?)\].*?\[\/group\]/'
 # "(?s)\\[group(.*?)\\].*?\\[/group\\]"
 # 

 (?s)
 \[group
 ( .*? )
 \]
 .*? 
 \[/group\]