首页 > 解决方案 > 在 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

如您所见,拆分后的数组包含与模式不匹配的字符串。如何避免打印正则表达式不匹配的文本?

标签: c#regexsplit

解决方案


似乎您误解了 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);


推荐阅读