C# 拆分由多个空格分隔的字符串,忽略单个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17731154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:20:34  来源:igfitidea点击:

Split string separated by multiple spaces, ignoring single spaces

c#regexsplit

提问by Rafael Montero

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.

但不成功,我只想用多个空格分割字符串,而不是单个空格。

采纳答案by dasblinkenlight

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

+表示“一个或多个”,因此单个空格可以作为分隔符。如果您想多次要求,请使用{m,n}

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

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

{m,n}表达需要的表达之前立即将其匹配mn倍以下。只需要一个限制。如果缺少上限,则表示“m或多次重复”。

回答by Jonesopolis

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

回答by Matt_Bro

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