[英]Regex.Replace using regular expression as replacement
我是 C# 編程語言的新手,遇到了以下問題,我有一個字符串“away 4 TH some more words” 。 我想刪除 4 和 TH 之間的空格。 我寫了一個正則表達式,它有助於確定“4 TH”是否在字符串中可用。
[0-9]+\s(th|nd|st|rd)
string result = "avanue 4 TH some more words";
var match = Regex.IsMatch(result,"\\b" + item + "\\b",RegexOptions.IgnoreCase) ;
Console.WriteLine(match);//True
C# 中是否有任何內容可以刪除空間
類似Regex.Replace(result, "[0-9]+\\s(th|nd|st|rd)", "[0-9]+(th|nd|st|rd)",RegexOptions.IgnoreCase);
所以最終結果看起來像
大道 4TH 更多的話
您可以使用
var pattern = @"(?i)(\d+)\s*(th|[nr]d|st)\b";
var match = string.Concat(Regex.Match(result, pattern)?.Groups.Cast<Group>().Skip(1));
請參閱產生 4TH 的4TH
演示。
正則表達式 - (?i)(\d+)\s*(th|[nr]d|st)\b
- 匹配將值捕獲到第 1 組的 1 個或多個數字,然后將 0 個或多個空格與\s*
匹配,然后將th
、 nd
、 rd
或st
作為整個單詞(因為\b
是單詞邊界)被捕獲到第 2 組中。
Regex.Match(result, pattern)?
部分嘗試匹配字符串中的模式。 如果匹配, Groups property is accessed and all groups are cast to a
list with
. Since the first group is the whole match value, we
. Since the first group is the whole match value, we
.Skip(1)` 它。
rest(組 1 和組 2 的值)與string.Concat
連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.