正则表达式匹配线与大括号

时间:2015-02-28 19:04:02

标签: javascript regex

我正在尝试编写一个正则表达式,它将基本上通过一个字符串并提取我稍后将使用的某些组。

我有一个我正在使用的示例字符串:

foo bar baz

foo {
    bar
    baz
} asdf

a {
    b
    c
} d

我希望输出匹配为:

  1. foo bar baz
  2. 下一步:

    foo {
        bar
        baz
    } asdf
    
  3. 最后:

    a {
        b
        c
    } d
    

    所以我一直在研究的正则表达式是:/(^[\s\S]+?\}|\S.+)\n?/g 但那仍然行不通。可以帮助正则表达式或建议使用JavaScript更好的方法吗?

2 个答案:

答案 0 :(得分:1)

我觉得这个任务的最佳正则表达式只是.*(在javascript中,.与换行符不匹配,因此.*基本上意味着整行。),以及逐行评估内容。正则表达式在嵌套匹配和解析它们时会遇到很多麻烦。

这样的事可能适合你:http://jsfiddle.net/qfLs7s01/3/。它是一个逐行非常简陋的解析器。

var funks = {} // this is an object to hold all the parsed out data
var funkname;
var nest = [];
var content = document.getElementById('container').value;
var cgather = content.replace(/(.*)/igm,function(match, p1) {
    p1 = p1.trim();
    if (p1.substr(p1.length-1,1) == "{") {
        funks[p1] = [];
        funkname = p1;
        nest.push(p1);
    } else if (p1.substr(0,1) == "}") {
        if (nest.length > 0) {
            funkname = nest[nest.length-2];
            nest.splice(-1,1);
        } else {
            nest = [];
        }
    } else {
        if (p1.length) funks[funkname].push(p1)
    }
    return p1;
})

console.log(funks);

唯一的麻烦是它如何处理重复的函数名称。

foo {
  foo content
} foo

bar {
  bar content
} bar

foo {
  more foo content
}

将生成像{foo: ["foo content","more foo content"], bar: ["bar content"]}

这样的数组结构

答案 1 :(得分:1)

尝试这种模式

([^{\r\n]+{[^}]+}.*|.+)

Demo


以下评论可以使用此模式

([^{}\r\n]*{[^{}]*}[^{}\r\n]*|.+)

Demo


新模式

((?:[^{}\r\n]*{[^{}]*}[^{}\r\n]*)+|.+)  

Demo

相关问题