Anjali5 Anjali5 - 1 month ago 4
ASP.NET (C#) Question

splitting the string that has more than or equal to two white spaces

I have a string. I want to split the string on uneven white spaces. if the white spaces are more or equal to 2 spaces in length than I want them to be in seperate array item, but if there is only one space then I want them to be in same array item so for e.g.

I have this string

1234 This is a Test PASS 1255432 12/21/2016 07:14:11


so when I split the above string, it should be like this

arr(0) = 1234
arr(1) = This is a test ' because it has only one space in between, it there are more or equal to two spaces than I want it to be a seperate item in an array
arr(2) = Pass
arr(3) = 1255432
arr(4) = 12/21/2016
arr(5) = 07:14:1


same thing with below string:

0001 This is a Marketing text_for the students TEST2 468899 12/23/2016 06:23:16


When I split the above string, it should like this:

arr(0)=0001
arr(1) = This is a Marketing text_for the students
arr(2) = Test2
arr(3)=468899
arr(4)=12/23/2016
arr(5) = 06:23:16


Is there any regular expression that can help me to split the string based on spaces, but put together the words if the space is more or equal to 2.

Any help will be greatly appreciated.

Answer

This can be done with this regex (\s{0,1}\S+)+ like so:

           string text = "0001  This is a Marketing text_for the students     TEST2              468899                           12/23/2016   06:23:16";
            Regex regex = new Regex(@"(\s{0,1}\S+)+");

            var matches = regex.Matches("0001  This is a Marketing text_for the students       TEST2              468899                           12/23/2016   06:23:16").Cast<Match>()
                                    .Select(m => m.Value)
                                      .ToArray();

            Console.WriteLine(String.Join( ",", matches));

This is a working java Script snippet of the same thing.

var value = "0001  This is a Marketing text_for the students       TEST2              468899                           12/23/2016   06:23:16";
var matches = value.match(
     new RegExp("(\\s{0,1}\\S+)+", "gi")
);
console.log(matches)

This regex (\s{0,1}\S+)+ works by matching 0 or 1 spaces at the begging of each match with \s{0,1} and then any number of things that aren't a space with \S+ it then matches this whole thing any number of times by containing it in parentheses and using the + operator (...)+, this allows for the string together of single spaces characters.