Split string separated by multiple spaces, ignorin

2020-03-01 07:30发布

问题:

I need to split a string separated by multiple spaces. For example:

"AAAA AAA        BBBB BBB BBB        CCCCCCCC"

I want to split it into these:

"AAAA AAA"   
"BBBB BBB BBB"
"CCCCCCCC"

I tried with this code:

value2 = System.Text.RegularExpressions.Regex.Split(stringvalue, @"\s+");

But not success, I only want to split the string by multiple spaces, not by single space.

回答1:

+ means "one or more", so a single space would qualify as a separator. If you want to require more than once, use {m,n}:

value2 = System.Text.RegularExpressions.Regex.Split( stringvalue, @"\s{2,}");

The {m,n} expression requires the expression immediately prior to it match m to n times, inclusive. Only one limit is required. If the upper limit is missing, it means "m or more repetitions".



回答2:

value2 = System.Text.RegularExpressions.Regex.Split( stringvalue, @"\s{2,}");


回答3:

value2 = System.Text.RegularExpressions.Regex.Split( stringvalue, @"\s\s+");


标签: c# regex split