Extract string between brackets

此生再无相见时 提交于 2021-02-11 12:40:25

问题


I would like to extract characters between first opening and last closing brackets in a string like match[input[name="firstname"]] considering the characters to retrieve may also contain more brackets. In this case it would get input[name="firstname"] Also, the string may contain some special characters like { # / \ ^


回答1:


This somehow awkward-looking regular expression

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

basically says "no brackets, then [, then no brackets, then ]".

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

To make this slightly more useful, here's how to extract topmost brackets' content from a string with respect to nesting:

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]]"]

Recursive matches support in a regex engine would allow to write that in one line, but javascript re's are not that advanced.




回答2:


This will match everything between the first occurrence of [ and the last ] in your string, no matter what characters are in between:

> 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"]"


来源:https://stackoverflow.com/questions/14536916/extract-string-between-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!