Extract multiple white spaces from a string

I want to get spaces that are longer than 1 space.

The following returns me the null characters between each letter, as well as spaces. However, I only want to highlight two lines of spaces between cand dand 3 lines of spaces between fand 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 to achieve this:

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

. The desired result will be List<string>, containing " "and" "

+4
source share
5 answers

If you want List<String>, as a result, you can 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();
+5
source

This will give you the 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);
+3
source

, Regex, Regex.Matches, , , - , , , ?

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

, MatchCollection, Regex.Matches, IEnumerable<Match>, OfType<> LINQ.

+2

,

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

, 2 .

+2

:

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


, .

+1

All Articles