如何使用 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/