使用正则表达式在JavaScript中获取花括号之间的内容

15
5个回答

40

这里是一个使用示例:

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

好的正则表达式。谢谢 :) - Tharanga

8

试试这个

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

例如:

欢迎使用由{gskinner.com}提供,由{ssd.sd}托管于Media Temple的RegExr v2.1!

它会返回'gskinner.com','ssd.sd'。

6
像这样吗?
var x="omg {wtf} bbq";

alert(x.match(/{([^}]+)}/));

返回的是{wtf},wtf而不是wtf - alex
获取第一个组,它将仅包含大括号之间的文本。请记住,正则表达式中的括号定义组。 - Santiago Palladino
我该如何一次性删除所有组并只返回“wtf”? - alex
刚在Firefox和Chrome中进行了测试,你遇到了什么错误?你使用的是和我相同的测试用例场景吗? - Khez

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上测试过,像这样:http://img801.imageshack.us/i/reie.png/,实际上我还测试了IE7、8,都可以正常工作。 - Linmic

0

这将返回一个匹配文本的数组。
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 , ''))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接