Javascript regex - 如何在大括号之间获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3354224/
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
Javascript regex - how to get text between curly brackets
提问by WastedSpace
I need to get the text (if any) between curly brackets. I did find this other post but technically it wasn't answered correctly: Regular expression to extract text between either square or curly brackets
我需要在大括号之间获取文本(如果有)。我确实找到了另一篇文章,但从技术上讲,它没有得到正确回答: Regular expression to extract text between any square or curlysacks
It didn't actually say how to actually extract the text. So I have got this far:
它实际上并没有说明如何实际提取文本。所以我已经走了这么远:
var cleanStr = "Some random {stuff} here";
var checkSep = "\{.*?\}";
if (cleanStr.search(checkSep)==-1) { //if match failed
alert("nothing found between brackets");
} else {
alert("something found between brackets");
}
How do I then extract 'stuff' from the string? And also if I take this further, how do I extract 'stuff' and 'sentence' from this string:
然后我如何从字符串中提取“东西”?而且,如果我更进一步,我如何从这个字符串中提取“东西”和“句子”:
var cleanStr2 = "Some random {stuff} in this {sentence}";
Cheers!
干杯!
回答by CMS
To extract all occurrences between curly braces, you can make something like this:
要提取大括号之间的所有匹配项,您可以执行以下操作:
function getWordsBetweenCurlies(str) {
var results = [], re = /{([^}]+)}/g, text;
while(text = re.exec(str)) {
results.push(text[1]);
}
return results;
}
getWordsBetweenCurlies("Some random {stuff} in this {sentence}");
// returns ["stuff", "sentence"]
回答by Jay
Create a "capturing group" to indicate the text you want. Use the String.replace() function to replace the entire string with just the back reference to the capture group. You're left with the text you want.
创建一个“捕获组”以指示您想要的文本。使用 String.replace() 函数仅使用对捕获组的反向引用替换整个字符串。你留下了你想要的文本。

