Skip to content
Advertisement

Match text between single quotes, double quotes, or no quotes at all

I’m trying to parse CLI-like arguments that could be enclosed in single quotes, double quotes, or no quotes at all.
Here’s an example of what I’m trying to get:

JavaScript

I’ve found a lot of similar questions, so this is what makes it different from them:

  • It’s important that it matches the arguments not in quotes too, and keeps the original order
  • It should be able to parse single and double quote arguments in the same string
  • It should not match the quotes themselves:
JavaScript
  • It should allow escape quotes and other quotes inside it:
JavaScript

I’ve tried using a lot of different Regex patterns I’ve found here but they all didn’t satisfy one of these conditions. I’ve also tried using libraries meant to parse CLI arguments, but it seems like they all rely on the process.argv (in Node.js), which is already split correctly based on the quotes, and so doesn’t help me.
What I essentially need to do is generate an array like process.argv.

It doesn’t need to be a single regex, a js/ts function that does the same it’s ok too.

Advertisement

Answer

“Verbose” expressions and named groups work especially well for tokenizing problems:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement