【问题标题】:Getting content between curly braces in JavaScript with regex使用正则表达式在 JavaScript 中的花括号之间获取内容
【发布时间】:2011-07-28 02:41:36
【问题描述】:

我正在尝试使用 JavaScript 在大括号之间获取内容。我找到了这个帖子:Regex to get string between curly braces "{I want what's between the curly braces}"

但我不知道如何应用像 /\{([^}]+)\}/ 这样的正则表达式

我尝试过string.replace('/\{([^}]+)\}/','');,但这不起作用。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    像这样?

    var x="omg {wtf} bbq";
    
    alert(x.match(/{([^}]+)}/));
    

    【讨论】:

    • 返回 {wtf},wtf 而不是 wtf
    • 获取第一组,它将只包含大括号之间的文本。请记住,正则表达式中的括号定义组。
    • 我怎样才能将所有组一起删除并让它返回wtf
    • 刚刚在 Firefox 和 Chrome 中进行了测试,您遇到了什么错误,您是否使用与我相同的测试用例场景?
    【解决方案2】:
    "{I want what's between the curly braces}".replace(/{(.*)}/, "$1");
    

    这应该可行,干杯。

    注意:你会在大括号中“获取所有内容”,即使它是一个空字符串。

    更新: 如果要匹配字符串中间的第一个字符,请使用“match”:

    "how are you {I want what's between the curly braces} words".match(/{(.*)}/)[1];
    

    你可以这样做:

    console.log("how are you {I want what's between the curly braces} words".match(/{(.*)}/));
    

    然后你会看到一个匹配项的列表,你可以随意利用它们。

    血腥细节:http://www.w3schools.com/jsref/jsref_obj_regexp.asp

    【讨论】:

    • @alex 你用的是什么版本的IE?我刚刚在IE9中测试过,像这样:img801.imageshack.us/i/reie.png,其实我也做过IE7、8,一切正常。
    【解决方案3】:

    这是一个使用示例:

    var found = [],          // an array to collect the strings that are found
        rxp = /{([^}]+)}/g,
        str = "a {string} with {curly} braces",
        curMatch;
    
    while( curMatch = rxp.exec( str ) ) {
        found.push( curMatch[1] );
    }
    
    console.log( found );    // ["string", "curly"]
    

    【讨论】:

    • 不错的正则表达式。谢谢。 :)
    【解决方案4】:

    试试这个

    /[^{\}]+(?=})/g
    

    例如

    欢迎使用由 Media Temple 主办的 {gskinner.com}、{ssd.sd} 提供的 RegExr v2.1!

    它将返回“gskinner.com”、“ssd.sd”

    【讨论】:

      【解决方案5】:

      这将返回一个匹配文本的数组。
      map 函数将返回没有{} 的文本。

      const text = "Regex to get string between curly braces {I want what's between the curly braces}"
      const result = text.match(/{([^}]+)}/g)
        .map(res => res.replace(/{|}/g , ''))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-29
        • 1970-01-01
        • 2015-07-05
        • 2015-02-01
        相关资源
        最近更新 更多