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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5520880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:28:09  来源:igfitidea点击:

Getting content between curly braces in JavaScript with regex

javascriptregexstring

提问by alex

I am trying to get content between curly braces with JavaScript. I found this thread: Regex to get string between curly braces "{I want what's between the curly braces}"

我正在尝试使用 JavaScript 获取大括号之间的内容。我找到了这个线程:正则表达式获取大括号之间的字符串“{我想要大括号之间的内容}”

But I do not know how to apply a regex like /\{([^}]+)\}/

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

I have tried string.replace('/\{([^}]+)\}/','');, however this does not work.

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

回答by meouw

Here's an example of use:

下面是一个使用示例:

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

回答by Khez

Like this?

像这样?

var x="omg {wtf} bbq";

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

回答by Mohamed Abo Elmagd

Try this

试试这个

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

for example

例如

Welcome to RegExr v2.1 by {gskinner.com}, {ssd.sd} hosted by Media Temple!

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

it will return 'gskinner.com', 'ssd.sd'

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

回答by Linmic

"{I want what's between the curly braces}".replace(/{(.*)}/, "");

this should work, cheers.

这应该有效,干杯。

Note: you'll "get everything" in the braces, even if it's an empty string.

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

Updated:If you are going to match the first character which in the middle of a string, use "match":

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

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

You can just do:

你可以这样做:

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

then you'll see a list of the match items, exploit them to whatever you want.

然后你会看到一个匹配项目的列表,你可以根据需要利用它们。

Gory details: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

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

回答by amir hosein ahmadi

This will return an array of matching text.
the map function will return the text without {}.

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