5

I'm using Regex.Split() to take the user input and turn it into individual words in a list but at the moment it removes any spaces they add, I would like it to keep the whitespace.

string[] newInput = Regex.Split(updatedLine, @"\s+");
1
  • 4
    How/where do you want to keep the whitespace? For example, what is the string " foo bar " supposed to split into?
    – BoltClock
    Commented Nov 20, 2011 at 20:04

2 Answers 2

8
string text = "This            is some text";
var splits = Regex.Split(text, @"(?=(?<=[^\s])\s+)");

foreach (string item  in splits)
    Console.Write(item);
Console.WriteLine(splits.Count());

This will give you 4 splits each having all the leading spaces preserved.

(?=\s+)

Means split from the point where there are spaces ahead. But if you use this alone it will create 15 splits on the sample text because every space is followed by another space in case of repeated spaces.

(?=(?<=[^\s])\s+)

This means split from a point which has non space character before it and it has spaces ahead of it.

If the text starts from a space and you want that to be captured in first split with no text then you can modify the expression to following

(?=(?<=^|[^\s])\s+)

Which means series of spaces need to have a non space character before it OR start of the string.

0
0

I'm guessing that some of the "words" you're interested in are actually phrases where spaces are acceptable. You can't easily use the space character as both a phrase delimiter and an allowable character within the phrase itself. Try using a comma for a delimiter instead:

string updatedLine = "user,input,two words,even three words";
string[] newInput = Regex.Split(updatedLine, @",");

This version of the regex allows trailing spaces after the commas:

string updatedLine = "user, input,   two words,    even three words";
string[] newInput = Regex.Split(updatedLine, @",\s+|,");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.