Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a substring between two special characters EXCLUDING the characters

So I want to capture the sub-string between two special characters in JavaScript, using regular expressions. Say I have the string "$Hello$, my name is $John$", I would want .match to return the array of [Hello, John]. *In addition, I do not want to capture the match between two matches. So I wouldn't want to capture $, my name is $, since it is technically between two '$'s.

The regular expression I have used is

var test = str.match(/(?<=\$)(.*)(?=\$)/);

Which works, but duplicates each entry twice. So it has [Hello, Hello, John, John]. I have also used var test = str.match(/(?<=\$)[^\$]+?(?=\$)/g) But this returns everything inbetween each match (the example i listed above $, my name is $.)

How can I fix this?

like image 436
kt-workflow Avatar asked Oct 15 '22 13:10

kt-workflow


1 Answers

You could match the first and the second dollar sign and use a capturing group to capture char is in between using a negated character class matching any char except a dollar sign.

\$([^$]+)\$

Regex demo

Instead of using match, you could use exec. For example:

var str = "$Hello$, my name is $John$";
var regex = /\$([^$]+)\$/g;
var m;
var test = [];

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  test.push(m[1]);
}

console.log(test);
like image 65
The fourth bird Avatar answered Oct 18 '22 13:10

The fourth bird