emihir0
emihir0

Reputation: 1250

Extracting a substring of a string, given the prior substring (flag?)

Let's say I have a string s = "xxx -I hello yyy and I want to extract hello given -I.

E.g. I'd like to make a function, say findToken that is:

function findToken(msg, flag, regexp) {
    return msg.match(new RegExp(flag + '\\s' + regexp, 'g'));
}

And then when I call findToken("xxx -I hello yyy", "-I", "\\w+"); I get now:

["-I hello"], however, I would like to get just ['hello'], ie. ignoring the flag. How would I accomplish this using RegExp?

Upvotes: 0

Views: 49

Answers (2)

KevBot
KevBot

Reputation: 18908

You can flip to using exec, add a capturing group, and return the first capture in a new array:

function findToken(msg, flag, regexp) {
  return [new RegExp(flag + '\\s(' + regexp + ')', 'g').exec(msg)[1]];
}

var result = findToken("xxx -I hello yyy", "-I", "\\w+");
console.log(result);

Upvotes: 1

LellisMoon
LellisMoon

Reputation: 5020

function findToken(msg, flag, regexp) {
var match=msg.match(new RegExp(flag + '\\s' + regexp, 'g'));
    return match[0].replace(flag+' ','');
}
console.log(findToken("xxx -I hello yyy", "-I", "\\w+"));

Upvotes: 1

Related Questions