Javascript正则表达式 - 如何在大括号之间获取文本 [英] Javascript regex - how to get text between curly brackets
问题描述
我需要在大括号之间获取文本(如果有的话)。我确实找到了这个其他帖子,但从技术上讲,它没有正确回答:
正则表达式,用于在方括号或大括号之间提取文本
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
它实际上并未说明如何实际提取文本。所以我有这么远:
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");
}
如何从字符串中提取东西?如果我进一步说明,如何从这个字符串中提取'stuff'和'sentence':
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}";
干杯!
推荐答案
要提取花括号之间的所有匹配项,你可以这样做:
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"]
这篇关于Javascript正则表达式 - 如何在大括号之间获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!