Reputation: 739
I have a string with a list of temperatures that can be in the negatives or positives.
Some of these temperatures will be separated by a whitespace, while some won't be.
i.e.: 19 20 22 -1 -3-4-10 -7 2 10
And I want to split that string by keeping only the values as such:
19
20
22
-1
-3
-4
-10
-7
2
10
Can anyone help me with that? I am not experienced with regular expressions.
Thank you VERY much in advance!
Cheers
Upvotes: 0
Views: 228
Reputation: 5414
you can use this regex
(?!-)|(?=-)
check this demo Demo
string temperatures = "19 20 22 -1 -3-4-10 -7 2 10";
string[] res = Regex.Split(temperatures, " (?!-)|(?=-)");
foreach (var item in res)
{
Console.WriteLine(item);
}
#19
#20
#22
#-1
#-3
#-4
#-10
#-7
#2
#10
Upvotes: 0
Reputation: 174706
Just split according to the below regex.
@"\s+|(?<!\s)(?=-)"
ie,
string[] split = Regex.Split(input_str, @"\s+|(?<!\s)(?=-)");
Upvotes: 3