c# - 在 C# 中仅保留 Regex.Split 的匹配模式
问题描述
我只想保留匹配的模式Regex.Split()
并丢弃其他文本。
例子
假设我只想打印文本中的大写单词。
Console.WriteLine("Give input");
string input = Console.ReadLine();
string pattern = @"([A-Z]{2,})";
string[] words = Regex.Split(input, pattern);
foreach (var w in words)
Console.WriteLine(w)
键入MY_NAME_IS_george_WHATS_YOUR_NAME 会提供如下输出。
Type an identifier
MY_NAME_IS_george_WHATS_YOUR_NAME
MY
_
NAME
_
IS
_george_
WHATS
_
YOUR
_
NAME
Type an identifier
如您所见,拆分后的数组包含与模式不匹配的字符串。如何避免打印正则表达式不匹配的文本?
解决方案
似乎您误解了 split 的作用。
在正则表达式模式定义的位置处将输入字符串拆分为子字符串数组。
如果您想拆分而不是打印唯一的大写字母,您还必须进行匹配
Console.WriteLine("Give input");
string input = Console.ReadLine();
string pattern = @"([A-Z]{2,})";
string[] words = Regex.Split(input, pattern);
foreach (var w in words)
if(Regex.IsMatch(w,pattern)
Console.WriteLine(w);
或者只是使用Regex.Matches(input,pattern);
推荐阅读
- html - 尽管没有填充,但 Div 空间
- python - 如何使用 Python 将新列附加到 csv?
- javascript - 追加来自多个表单的数据以将所有记录存储在 json 中
- shell - Shell Scripting - 列出目录中文件的标题行
- xpath - 计算包含两组 1 且由 0 分隔的列表中 1 的数量
- sql - 从具有两个父级的子表中删除,而无需在 sql server 中进行级联删除
- http - 如何处理通过 HTTP 上传的大文件而不将请求存储在临时文件中
- ios - 在哪些情况下需要使用 MTLStoreActionStoreAndMultisampleResolve 而不是 MTLStoreActionMultisampleResolve?
- ruby-on-rails - 让用户在 Rails 应用程序中下载 CSV 文件
- c++ - 使用指针迭代一系列原始类型声明?