简体   繁体   English

如何使用Regex分割字符串并包含空格

[英]How to use Regex to split a string AND include whitespace

I can't seem to find (or write) a simple way of splitting the following sentence into words and assigning a word to the whitespace between the letters. 我似乎找不到(或编写)将以下句子拆分为单词并将单词分配给字母之间的空白的简单方法。 (VS 2010, C#, .net4.0). (VS 2010,C#、. net4.0)。

String text = "This is a test.";

Desired result: 
[0] = This
[1] = " "
[2] = is
[3] = " "
[4] = a
[5] = " "
[6] = test.

The closest I have come is: 我最接近的是:

  string[] words = Regex.Split(text, @"\s");

but ofcourse, this drops the whitespace. 但当然,这会删除空白。

Suggestions are appreciated. 建议表示赞赏。 Thanks 谢谢

Edit: There may be one or more spaces between the words. 编辑:单词之间可能有一个或多个空格。 I would like all spaces between the words to be returned as a "word" itself (with all spaces being placed in that "word"). 我希望单词之间的所有空格都作为“单词”本身返回(所有空格都放在该“单词”中)。 eg, if 5 spaces between a word would be. 例如,如果一个单词之间有5个空格。

String spaceword = " "; 字符串spaceword =“”; <--This is not showing correctly, there should be a string of 5 spaces. <-此显示不正确,应包含5个字符串。

You can use LINQ to add spaces manually between them: 您可以使用LINQ在它们之间手动添加空格:

var parts = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = parts.SelectMany((x,idx) => idx != parts.Length - 1 
                                         ? new[] { x, " " }
                                         : new[] { x }).ToList();

Change your pattern to (\\s+) : 将模式更改为(\\s+)

        String text = "This        is a   test.";
        string[] words = Regex.Split(text, @"(\s+)");
        for(int i =0; i < words.Length;i++)
        {
            Console.WriteLine(i.ToString() + "," + words[i].Length.ToString() + " = " + words[i]);
        }

Here's the output: 这是输出:

0,4 = This
1,8 =         
2,2 = is
3,1 =  
4,1 = a
5,3 =    
6,5 = test.

You can try this regex, \\w+|\\s+ which uses or operator | 您可以尝试使用或运算符| \\w+|\\s+正则表达式|

var arr = Regex.Matches(text, @"\S+|\s+").Cast<Match>()
                                         .Select(i => i.Value)
                                         .ToArray();

It just matches both words and spaces and some LINQ stuff is being used so arr is just a String Array 它只匹配单词和空格,并且使用了一些LINQ东西,因此arr只是一个String Array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM