【问题标题】:Keep only matched patterns of Regex.Split in C#在 C# 中仅保留 Regex.Split 的匹配模式
【发布时间】:2020-05-29 10:06:26
【问题描述】:

我只想保留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

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

【问题讨论】:

  • 使用 Regex.Match 并从匹配中检索组。
  • 也许你的意思是Regex.Matches
  • 如果Stefano的回答解决了问题,能否请您采纳,谢谢!

标签: c# regex split


【解决方案1】:

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

【讨论】:

  • foreach (Match m in Regex.Matches("MY_NAME_IS_george_WHATS_YOUR_NAME", @"([A-Z]{2,})")) Console.WriteLine(m.Groups[0].Captures[0].Value);
  • Guys Regex.Matches(input,pattern) 返回一个包含所有匹配字符串的集合。
  • 顺便说一句,我赞成的只是因为我确实似乎误解了 split 的作用:D
  • @Longoon12000 随意添加到我的简单“只需使用Regex.Matches(input,pattern);
猜你喜欢
  • 1970-01-01
  • 2017-09-30
  • 2013-03-18
  • 1970-01-01
  • 2022-07-07
  • 2015-11-10
  • 2020-02-09
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多