【问题标题】:splitting the string that has more than or equal to two white spaces拆分大于或等于两个空格的字符串
【发布时间】:2025-12-16 17:00:02
【问题描述】:

我有一个字符串。我想在不均匀的空白处拆分字符串。如果空格的长度大于或等于 2 个空格,则我希望它们位于单独的数组项中,但如果只有一个空格,则我希望它们位于相同的数组项中,例如

我有这个字符串

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

所以当我拆分上面的字符串时,应该是这样的

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

与下面的字符串相同:

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

当我拆分上面的字符串时,它应该是这样的:

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

是否有任何正则表达式可以帮助我根据空格拆分字符串,但如果空格大于或等于 2,则将单词放在一起。

任何帮助将不胜感激。

【问题讨论】:

  • @"\s{2,}"拆分
  • 这样很多数组项将是空的。我可以得到我上面提到的东西吗
  • 你肯定还没试过。 regex101.com/r/7aBvcg/1

标签: asp.net regex


【解决方案1】:

这可以用这个正则表达式 (\s{0,1}\S+)+ 来完成,如下所示:

           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));

这是一个工作的 java Script sn-p 相同的东西。

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)

这个正则表达式(\s{0,1}\S+)+ 的工作原理是在每次匹配的开始时用 \s{0,1} 匹配 0 或 1 个空格,然后用 \S+ 匹配任意数量的不是空格的东西然后匹配整个东西通过将其包含在括号中并使用 + 运算符 (...)+ 任意次数,这允许将单个空格字符组合在一起的字符串。

【讨论】:

    最近更新 更多