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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With