[英]Use regex to split a string by {curly} substrings but include the { }
[英]How to use Regex to split a string AND include whitespace
我似乎找不到(或编写)将以下句子拆分为单词并将单词分配给字母之间的空白的简单方法。 (VS 2010,C#、. net4.0)。
String text = "This is a test.";
Desired result:
[0] = This
[1] = " "
[2] = is
[3] = " "
[4] = a
[5] = " "
[6] = test.
我最接近的是:
string[] words = Regex.Split(text, @"\s");
但当然,这会删除空白。
建议表示赞赏。 谢谢
编辑:单词之间可能有一个或多个空格。 我希望单词之间的所有空格都作为“单词”本身返回(所有空格都放在该“单词”中)。 例如,如果一个单词之间有5个空格。
字符串spaceword =“”; <-此显示不正确,应包含5个字符串。
您可以使用LINQ
在它们之间手动添加空格:
var parts = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = parts.SelectMany((x,idx) => idx != parts.Length - 1
? new[] { x, " " }
: new[] { x }).ToList();
将模式更改为(\\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]);
}
这是输出:
0,4 = This
1,8 =
2,2 = is
3,1 =
4,1 = a
5,3 =
6,5 = test.
您可以尝试使用或运算符|
\\w+|\\s+
正则表达式|
var arr = Regex.Matches(text, @"\S+|\s+").Cast<Match>()
.Select(i => i.Value)
.ToArray();
它只匹配单词和空格,并且使用了一些LINQ东西,因此arr
只是一个String
Array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.