Regexp将项目提取为多维数组

时间:2015-04-11 19:37:27

标签: javascript regex

我不知道该怎么做,但我想从每个if/elseif行获取表达式。

我可以使用以下两行来提取它们:

var ifreg = /\{if\s+?(.+?)\}([\s\S]+?)\{else/ig.exec(block);
var elseifreg = /\{elseif\s+?(.+?)\}([\s\S]+?)\{else/ig.exec(block);

但结果并不漂亮(第二次曝光):

[ '{elseif 2 == 2}\n            Two is equal to two\n        {else',
'2 == 2',
'\n            Two is equal to two\n        ',
index: 52,
input: '{if 1 == 2}\n            One is equal to two\n        {elseif 2 == 2}\n            Two is equal to two\n        {elseif 4 != 5}\n            Four does not equal five\n        {else}\n            Something went wrong...\n        {/if}' ]

这是我正在搜索的teplate:

{if 1 == 2}
    {foreach $row in $items}
        I am here
    {/foreach}
{elseif $item == 2}
     {$item} is equal to two
{elseif 4 != 5}
     Four does not equal five
{else}
    Something went wrong...
{/if}

我想要完成的是使用一个表达式获得所有结果,并使结果看起来像这样(不必完全相同但接近):

[
    ['1 == 2', '{foreach $row in $items}
        I am here
    {/foreach}'],
    ['$item == 2', '{$item} is equal to two'],
    ['4 != 5', 'Four does not equal five'],
    ['Something went wrong...']
]

我能做些什么来完成这项工作?

2 个答案:

答案 0 :(得分:2)

指定 str 是您的字符串。 newlines是可选的

var results = []
str.match(/\{[^{}]+/g).forEach(function(a,b) {
    results[b]=[a.replace(/(?:if|else|elseif|\/if|\{)\s?/g, '')];
    results[b][0]===''&&results[b].splice(0,1);
});
str.match(/[^{}]+\{/g).forEach(function(a,b) {
    results[b].push(a.substring(0,a.length-1).trim());
});
results.pop();

results的值为:

[
    [
        "1 == 2",
        "One is equal to two"
    ],
    [
        "2 == 2",
        "Two is equal to two"
    ],
    [
        "4 != 5",
        "Four does not equal five"
    ],
    [
        "Something went wrong..."
    ]
]

答案 1 :(得分:1)

这不仅仅是一个正则表达式,但我会尝试这样的事情:

  var block='{if 1 == 2}\n            One is equal to two\n        {elseif 2 == 2}\n            Two is equal to two\n        {elseif 4 != 5}\n            Four does not equal five\n        {else}\n            Something went wrong...\n        {/if}';
var reg=/\{(?:else|(?:else)?if\s+(.+)*)\}\s*([^{]+)[\s]*\n/igm

var results = []
for (var result = reg.exec(block); result != null; result = reg.exec(block))
{
    var innerResult=[]
    if (result!=null && result.length > 1 && result[1]!=undefined) innerResult.push(result[1]);
    if (result!=null && result.length > 2 && result[2]!=undefined) innerResult.push(result[2]);
    if (innerResult.length>0) results.push(innerResult);
}