0

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

4

2 回答 2

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 re 并不是那么先进。

于 2013-01-26T12:25:23.933 回答
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"]"
于 2013-01-26T12:31:41.053 回答