srini.rgs
srini.rgs

Reputation: 13

Capture Groups with Multiple Delimiters

In Javascript, I have ascii text lines, and each line can have multiple groups of $ delimited text, as shown below.


Input Text: In the quadratic polynomial $ax^2 + bx + c$, $a$ should not be $0$


I need a performant way of creating an array, which should have either words or the delimited string. For example, after parsing the above line, I need to end up with


Desired Result: ["In", "the", "quadratic", "polynomial", "$ax^2 + bx + c$", "," "$a$", "should", "not", "be", "$0$]


Pattern that is not helping: "\\$(.|\v)*?\\$"


Basically, I need to parse the string and pull out words which are space or tab separated, but I have to treat $ delimited text as a single word.

But that is really the end of my wits. Please help :-)

Upvotes: 0

Views: 242

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You might use

\$[^$]*\$|\S+
  • \$ Match a $
  • [^$]* Match 0+ times any char except $ (or use [^$\r\n]* to not cross newlines)
  • \$ Match a $
  • | Or
  • \S+ Match 1+ whitespace chars

Regex demo

const regex = /\$[^$]*\$|\S+/g;
const s = "In the quadratic polynomial $ax^2 + bx + c$, $a$ should not be $0$";
console.log(s.match(regex));

Upvotes: 2

Related Questions