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
"${spurs."
"}"
I have tried const regex = /[$]{spurs.+?[}]/gi
but it doesn't require the square brackets it seems optional. Any ideas?
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));
Use the following:
\${spurs.*\[(.*)\]\}
\$
- literal dollar
spurs.*\[
- 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 :
Try this solution which uses the match()
method(more info on it here ):
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.