Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with variable number of spaces [duplicate]

Tags:

c#

regex

I'm trying to split a string like this:

7       300685  1235    200017  200018  200019

In

7
300685
1235
200017
200018
200019

array of strings.

I've come up with this Regex but it keeps the white spaces too:

var myStrings = System.Text.RegularExpressions.Regex.Split(linea, @"\s+");

That's because I target any string that preceeds a white space. How to not to do that and keep only not white strings.

I know that it is easily done by removing empty strings from the array but I would like to do it with the regular expression.

like image 622
Sturm Avatar asked Mar 28 '26 18:03

Sturm


2 Answers

You can use StringSplitOptions.RemoveEmptyEntries enumeration with String.Split method like;

The return value does not include array elements that contain an empty string

string s = "7       300685  1235    200017  200018  200019";
var array = s.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
    Console.WriteLine(item);
}

Output will be;

7
300685
1235
200017
200018
200019

Here a demonstration.

like image 93
Soner Gönül Avatar answered Mar 30 '26 08:03

Soner Gönül


Why don't you just use String.Split method ?

var myStrings = linea.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

Another way with Split and LINQ without RemoveEmptyEntries option:

var myStrings = linea.Split().Where(x => x.All(char.IsDigit)).ToArray();

Also there is a RegexOption.IgnorePatternWhitespace parameter that you can pass your Regex.Split method to remove whitespaces:

var myStrings = Regex.Split(linea, @"\s+", RegexOptions.IgnorePatternWhitespace);
like image 26
Selman Genç Avatar answered Mar 30 '26 06:03

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!