Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string separated by multiple spaces, ignoring single spaces

Tags:

c#

regex

split

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.

like image 397
Rafael Montero Avatar asked Jul 18 '13 18:07

Rafael Montero


People also ask

How do you remove spaces in Split?

To split the sentences by comma, use split(). For removing surrounding spaces, use trim().

How do you split a string at spaces in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);


1 Answers

+ 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".

like image 111
Sergey Kalinichenko Avatar answered Sep 23 '22 21:09

Sergey Kalinichenko