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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay