13

I need to split a string like the one below, based on space as the delimiter. But any space within a quote should be preserved.

research library "not available" author:"Bernard Shaw"

to

research
library
"not available"
author:"Bernard Shaw"

I am trying to do this in C Sharp, I have this Regex: @"(?<="")|\w[\w\s]*(?="")|\w+|""[\w\s]*""" from another post in SO, which splits the string into

research
library
"not available"
author
"Bernard Shaw"

which unfortunately does not meet my exact requirements.

I'm looking for any Regex, that would do the trick.

Any help appreciated.

AkiRoss
  • 11,745
  • 6
  • 59
  • 86
itsbalur
  • 992
  • 3
  • 17
  • 39

2 Answers2

32

As long as there can be no escaped quoted inside quoted strings, the following should work:

splitArray = Regex.Split(subjectString, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

This regex splits on space characters only if they are preceded and followed by an even number of quotes.

The regex without all those escaped quotes, explained:

(?<=      # Assert that it's possible to match this before the current position (positive lookbehind):
 ^        # The start of the string
 [^"]*    # Any number of non-quote characters
 (?:      # Match the following group...
  "[^"]*  # a quote, followed by any number of non-quote characters
  "[^"]*  # the same
 )*       # ...zero or more times (so 0, 2, 4, ... quotes will match)
)         # End of lookbehind assertion.
[ ]       # Match a space
(?=       # Assert that it's possible to match this after the current position (positive lookahead):
 (?:      # Match the following group...
  [^"]*"  # see above
  [^"]*"  # see above
 )*       # ...zero or more times.
 [^"]*    # Match any number of non-quote characters
 $        # Match the end of the string
)         # End of lookahead assertion
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • How to split it with dots, question marks, exclamation marks etc. instead of spaces. I'm trying to get every sentence one by one except inside of quotes. For example: Walked. **Turned back.** But why? **And said "Hello world. Damn this string splitting things!" without a shame.** – ErTR Jan 26 '16 at 00:25
  • 1
    @ErtürkÖztürk: That's worthy of its own StackOverflow question - too big to be answered in a comment. – Tim Pietzcker Jan 26 '16 at 07:12
  • 2
    @TimPietzcker well I don't know why but I asked nearly same question (http://stackoverflow.com/questions/33886103/how-to-find-recurring-word-groups-in-text-with-c) and I got too much reaction like "here's not a code writing service" or "it's not clear" so I'm trying my chance in comments. – ErTR Jan 26 '16 at 14:34
3

Here you go:

C#:

Regex.Matches(subject, @"([^\s]*""[^""]+""[^\s]*)|\w+")

Regular expression:

([^\s]*\"[^\"]+\"[^\s]*)|\w+
Joel Rein
  • 3,608
  • 1
  • 26
  • 32