Search code examples
javascriptregexparsingtext-parsing

Could a regular expression be used to find text between pairs of delimiters


I need to parse an email template for custom variables that occur between pairs of dollar signs, e.g:

$foo$bar$baz$foo$bar$baz$wtf

So I would want to start by extracting 'foo' above, since it comes between the first pair (1st and 2nd) of dollar signs. And then skip 'bar' but extract 'baz' as it comes between the next pair (3rd and 4th) of dollar signs.

I was able to accomplish this with split and filter as below, but am wondering, if there's a way to accomplish the same with a regular expression instead? I presume some sort of formal parser, recursive or otherwise, could be used, but that would seem like overkill in my opinion

const body = "$foo$bar$baz$foo$bar$baz$wtf";
let delimitedSegments = body.split('$');

if (delimitedSegments.length % 2 === 0) {
  // discard last segment when length is even since it won't be followed by the delimiter
  delimitedSegments.pop();
}

const alternatingDelimitedValues = delimitedSegments.filter((segment, index) => {
  return index % 2;
});
console.log(alternatingDelimitedValues);

OUTPUT: [ 'foo', 'baz', 'bar' ]

Code also at: https://repl.it/@dexygen/findTextBetweenDollarSignDelimiterPairs


Solution

  • Just match the delimiter twice in the regexp

    const body = "$foo$bar$baz$foo$bar$baz$wtf";
    const result = body.match(/\$[^$]*\$/g).map(s => s.replace(/\$/g, ''));
    console.log(result);