Sample input string
"Hi ${spurs.stadium[capacity]}" to return "${spurs.stadium[capacity]}"
"Hi ${spurs.stadium}" to return ""
"Hi ${spurs.stadium{capacity}}" to return ""
So I am looking for pattern where
- string starts with
"${spurs."
- string must contain after this square brackets which can have any content
- end with
"}"
I have tried const regex = /[$]{spurs. ?[}]/gi
but it doesn't require the square brackets it seems optional. Any ideas?
CodePudding user response:
You want to match by order of appearance. Left to right.
EDIT: added a lazy (not greedy) quantifier ?
var str = "Hi ${spurs.stadium[capacity]} dog" // to return "${spurs.stadium[capacity]}"
var str2 = "Hi ${spurs.stadium}" // to return ""
var str3 = "Hi ${spurs.stadium{capacity}}" // to return ""
var str4 = "Hi ${spurs.stadium[capacity]} ${spurs.stadium[crowd]}";
const regex = /\${spurs\..*?\[.*?\]}/gi
console.log(str.match(regex));
console.log(str2.match(regex));
console.log(str3.match(regex));
console.log(str4.match(regex));
CodePudding user response:
Use the following:
\${spurs.*\[(.*)\]\}
\$
- literal dollarspurs.*\[
- spurs and any character after until opening square bracket(.*)\]
- any character until closing square bracket (saved in a capture group for extraction later, if needed\}
- closing bracket
Here is a working example:
CodePudding user response:
Try this:
const paragraph = '"Hi ${spurs.stadium[capacity]}" to return "${spurs.stadium[capacity]}" "Hi ${spurs.stadium}" to return "" "Hi ${spurs.stadium{capacity}}" to return ""';
const regex = /{.*?}/g;
const found = paragraph.match(regex);
console.log(found);