Home > Mobile >  JS Regex to match a start and end pattern plus contain square brackets
JS Regex to match a start and end pattern plus contain square brackets

Time:07-14

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

  1. string starts with "${spurs."
  2. string must contain after this square brackets which can have any content
  3. 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.*\[(.*)\]\}

  1. \$ - literal dollar

  2. spurs.*\[ - spurs and any character after until opening square bracket

  3. (.*)\] - any character until closing square bracket (saved in a capture group for extraction later, if needed

  4. \} - 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);

  • Related