DEV Community

Cover image for Regex split by spaces except inside quote marks
Adam K Dean
Adam K Dean

Posted on

2

Regex split by spaces except inside quote marks

Here's a nifty little bit of code I just wrote while writing a console input handler. Sometimes you will want to split up a string by a space, but then how do you input more than one word as a single argument? You put it in quote marks, but then how do you split those separately? Like this:

MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Enter fullscreen mode Exit fullscreen mode

Yep, one line of code. Don't forget to include System.Text.RegularExpressions though!

Lets take it further for a little test (actually the test code I was using):

MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");
WriteToConsole("Match Count: {0}", matches.Count);

foreach (Match match in matches) WriteToConsole(match.ToString());
Enter fullscreen mode Exit fullscreen mode

Input:

The "quick brown fox" jumps over "the lazy dog"

Output:

Match Count: 5
The
"quick brown fox"
jumps
over
"the lazy dog"

So there you have it, probably the easiest way to do it.

Enjoy

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay