提取括号之间的字符串 [英] Extract string between brackets

查看:71
本文介绍了提取括号之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 { # / \ ^

推荐答案

这个看起来有点尴尬的正则表达式

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

正则表达式引擎中的递归匹配支持允许将其写在一行中,但 javascript re 并没有那么先进.

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

这篇关于提取括号之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆