简体   繁体   中英

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

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?

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.*\[(.*)\]\}

  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 :

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM