在括号之间提取字符串

时间:2013-01-26 12:23:56

标签: javascript regex string pattern-matching

我想在match[input[name="firstname"]]之类的字符串中提取第一个开头和最后一个右括号之间的字符,因为要检索的字符也可能包含更多括号。在这种情况下,它将获得input[name="firstname"]此外,该字符串可能包含一些特殊字符,如{ # / \ ^

2 个答案:

答案 0 :(得分:3)

这看起来很尴尬的正则表达式

/[^[\]]+\[[^[\]]+\]/

基本上说“没有括号,然后[,然后没有括号,那么]”。

s = 'match[input[name="firstname"]]'
> "match[input[name="firstname"]]"
re = /[^[\]]+\[[^[\]]+\]/
> /[^[\]]+\[[^[\]]+\]/
s.match(re)
> ["input[name="firstname"]"]

为了使这个更有用,下面是如何从字符串中提取最上面的括号内容相对于嵌套:

function extractTopmostBrackets(text) {
    var buf = '', all = [], depth = 0;
    text.match(/\]|\[|[^[\]]+/g).forEach(function(x) {
        if(x == '[')
            depth++;
        if(depth > 0)
            buf += x;
        if(x == ']')
            depth--;
        if(!depth && buf)
            all.push(buf), buf = '';
    })
    return all;
}

text = "foo [ begin [bar [baz] [spam]] end ] stuff [one [more]]"

console.log(extractTopmostBrackets(text))
// ["[ begin [bar [baz] [spam]] end ]", "[one [more]]"]

正则表达式引擎中的递归匹配支持允许在一行中写入,但是javascript不是那么高级。

答案 1 :(得分:1)

这将匹配字符串中第一次出现[和最后]之间的所有内容,无论中间是什么字符:

> s = 'match[input[name="firstname"]]'
"match[input[name="firstname"]]"
> re = /\[(.*)\]/
/\[(.*)\]/
> q = s.match(re)
["[input[name="firstname"]]", "input[name="firstname"]"]
> q[1]
"input[name="firstname"]"