Home > Software design >  Why find between brackets is matching wrong when I have more than one match?
Why find between brackets is matching wrong when I have more than one match?

Time:12-19

I try to find the text between two brackets and get them into array.

To do that, I use this regex: /\{\{([^)] )\}\}/. (it matches the text between two brackets).

But when I have more than one match, it does the match wrong.

Why? it is because the regex is incorrect, or do I need to use some regex flag?

I was expecting to get an array of foo and bar.

 const a = 'text:{{ foo }} {{bar}}';
const b = a.match(/\{\{([^)] )\}\}/);
console.log(b);

My final goal is to transform this text: text:{{ foo }} {{bar}} to 'text:' foo bar. this is mean I want to strip out the brackets and wrap the what is not brackets with a quote and contact them with a plus character.

To do that I want to find foo and bar and then split the text with the results and contact them.

CodePudding user response:

I once had to do a task which required me to use a regex like yours to find and replace text between brackets, i wrote a one-liner function to do so and i'm posting it as an answer for future reference

/**
 * @param str - The string to parse
 * @param conf - The object to get "variables" from (eg: { name: 'John' } would be the object if the string was 'Hello {{name}}')
 */
const parse = (str, conf) => str.replace(/{{(?<sc>[a-z] )}}/g, (substr, match) => conf[match] ?? substr);

In your case you can use something like that:

const a = 'text:{{ foo }} {{bar}}'
const b = a.match(/(?<=\{\{\s*)\w (?=\s*\}\})/g)
console.log(b) // output: ['foo', 'bar']

Explanation:

  • (?<=\{\{\s*): this is a positive look-behind, it assert that the match is preceded by the regex between brackets, in this case i look for {{ followed by 0 or more spaces
  • \w : matches any word character (foo, bar)
  • (?=\s*\}\}): this does the same as the first group but it assert that the match is followed by the match between brackets, in this case i look for 0 or more spaces and then }}
  • g: is the global modifier, i added it since i want to match all occurences of this regex and not stop after the first match
  • Related