簡體   English   中英

在 C# 中只保留 Regex.Split 的匹配模式

[英]Keep only matched patterns of Regex.Split in C#

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM