Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract multiple white spaces from string

Tags:

c#

regex

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 " "

like image 419
David Klempfner Avatar asked Dec 10 '22 21:12

David Klempfner


2 Answers

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();
like image 157
Dmitry Bychenko Avatar answered Dec 20 '22 17:12

Dmitry Bychenko


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);
like image 30
azt Avatar answered Dec 20 '22 16:12

azt