kt-workflow
kt-workflow

Reputation: 359

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?

Upvotes: 5

Views: 2369

Answers (3)

The fourth bird
The fourth bird

Reputation: 163297

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);

Upvotes: 2

CinCout
CinCout

Reputation: 9619

Can achieve it without employing lookbehinds:

(?:.*?\$(.*?)\$) /g

All I am doing is lazily looking for a $, and then capturing everything lazily until the next $ is encountered. This is repeated several times via the /g flag. Each capturing group will then have the desired string.

Demo

Upvotes: 0

ldtcoop
ldtcoop

Reputation: 680

I was able to get the desired matches with /(?<=\$)[^$ ]+(?=\$)/g.

It will match every word between two dollar signs, but it relies on two assumptions. The first is that $ can't appear as a character in the sentence, e.g. $Your$ total is $4.50, cash or $card$. The second is that there will never be a space inside the dollar signs, e.g. $Hello$, my name is $John Smith$. As long as that works, you should be good to go.

Upvotes: 1

Related Questions