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");
}
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!
To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.
The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".
A bracket expression is either a matching list expression or a non-matching list expression. It consists of one or more expressions: ordinary characters, collating elements, collating symbols, equivalence classes, character classes, or range expressions.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With