c# - 正则表达式按空格将字符串拆分为单词并包含字符

标签 c# regex

如何使用 Regex.Split(input, pattern) 方法执行此拆分?

This is a [normal string ] made up of # different types # of characters

字符串数组输出:

1. This 
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

它还应该保留前导空格,所以我想保留所有内容。一个字符串包含 20 个字符,字符串数组的所有元素总共应包含 20 个字符。

我尝试过的:

Regex.Split(text, @"(?<=[ ]|# #)")

Regex.Split(text, @"(?<=[ ])(?<=# #")

最佳答案

我建议匹配,即提取单词,而不是分割:

string source = @"This is a [normal string ] made up of # different types # of characters";

// Three possibilities:
//   - plain word [A-Za-z]+
//   - # ... # quotation
//   - [ ... ] quotation  
string pattern = @"[A-Za-z]+|(#.*?#)|(\[.*?\])";

var words = Regex
  .Matches(source, pattern)
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, words
  .Select((w, i) => $"{i + 1}. {w}")));

结果:

1. This
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

关于c# - 正则表达式按空格将字符串拆分为单词并包含字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48766643/

相关文章:

javascript - 正则表达式模式中的连接变量

JavaScript 正则表达式 : Finding a String that does not contain </p>

java - 二叉树是否包含另一棵树?

c# - 如何创建 WPF 形状编辑器?

c# - 无法在客户端 PC 上安装 .NET 应用程序

c# - ASPX C# 页面超时

c# - PS3 上 Mono 的开发资源

javascript - 如何在不同长度的文本周围创建//的注释 block

regex - pyspark 不支持正则表达式

c# - 尝试了解 c# 中的新异步功能