David Klempfner
David Klempfner

Reputation: 9940

Extract multiple white spaces from string

I want to get white spaces which are greater than 1 space long.

The following gets me the null chars between each letter, and also the white spaces. However I only want to extract the two white spaces string between c and d, and the 3 white spaces string between f and g.

string b = "ab c  def   gh";
List<string> c = Regex.Split(b, @"[^\s]").ToList();

UPDATE: The following works, but I'm looking for a more elegant way of achieving this:

c.RemoveAll(x => x == "" || x == " ");

The desired result would be a List<string> containing " " and " "

Upvotes: 5

Views: 127

Answers (5)

BhushanK
BhushanK

Reputation: 1243

You can use the following single line :

var list =Regex.Matches(value,@"[ ]{2,}").Cast<Match>().Select(match => match.Value).ToList();


Hope it will help you.

Upvotes: 1

Jon G
Jon G

Reputation: 4164

Rather than splitting using a Regex, try using Regex.Matches to get all items matching your pattern - in this case I've used a pattern to match two or more whitespace characters, which I think is what you want?

    var matchValues = Regex.Matches("ab c   def    gh", "\\s\\s+")
        .OfType<Match>().Select(m => m.Value).ToList();

Annoyingly, the MatchCollection returned by Regex.Matches isn't IEnumerable<Match>, hence the need to use OfType<> in the LINQ expression.

Upvotes: 2

azt
azt

Reputation: 2130

This should give you your desired List.

string b = "ab c  def   gh";
var regex = new Regex(@"\s\s+");
var result = new List<string>();
foreach (Match m in regex.Matches(b))
    result.Add(m.Value);

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

If you want List<String> as a result you could execute this Linq query

string b = "ab c  def   gh";

List<String> c = Regex
  .Matches(b, @"\s{2,}")
  .OfType<Match>()
  .Select(match => match.Value)
  .ToList();

Upvotes: 5

pzelasko
pzelasko

Reputation: 2322

If all you are interested in are these groups of whitespaces, you could use

foreach(var match in Regex.Matches(b, @"\s\s+")) {
    // ... do something with match
}

This guarantees that you will match at least 2 whitespaces.

Upvotes: 2

Related Questions