簡體   English   中英

正則表達式查找具有特定字符的單詞

[英]Regex to find words with specific character

如何查找其中包含特定字母的所有單詞?

例如,如果我的字符串是

This is a Station called South Yarra

然后我要提取所有帶有字母“ a”的單詞。 比賽將是

"a", "Station", "called", "Yarra"

到目前為止,我已經嘗試過

Regex regex = new Regex(@"\w[a]\w");

Regex regex = new Regex(@"\s[a*]\s");

嘗試使用以下正則表達式

Regex regex = new Regex(@"[^\s]*[a][^\s]*");

使用Linq不使用正則表達式的解決方案:

List<string> arr = s.Split(' ').Where(x => x.Contains('a')).ToList();

string.Split(' ') :它將返回字符串數組,其中包含此實例中由''分隔的子字符串

Enumerable.Where(predicate) :基於謂詞的過濾器序列

Enumerable.Contains() :確定序列是否包含指定的元素

POC: .net小提琴

根據您要如何處理標點符號(例如連字號),請考慮僅使用\\w*a\\w*

僅供參考: \\w匹配單詞字符。

暫無
暫無

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

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