正则表达式使用正则表达式替换

时间:2020-06-03 13:39:39

标签: c# regex algorithm collections

我是C#编程语言的新手,遇到以下问题 我有一个字符串“大道4号,还有一些单词” 。我想删除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);

所以最终结果看起来像

第四大道还有一些话

1 个答案:

答案 0 :(得分:0)

您可以使用

var pattern = @"(?i)(\d+)\s*(th|[nr]d|st)\b";
var match = string.Concat(Regex.Match(result, pattern)?.Groups.Cast<Group>().Skip(1));

请参见C# demo,产生4TH

正则表达式-(?i)(\d+)\s*(th|[nr]d|st)\b-将捕获值的1个或多个数字匹配到组1中,然后将0个或多个空格与\s*匹配,然后将th,{{1} },ndrd作为整个单词(因为st是单词边界)被捕获到第2组中。

\b部分尝试匹配字符串中的模式。如果存在匹配项,则匹配对象Regex.Match(result, pattern)? Group Groups property is accessed and all groups are cast to a Groups.Cast()list with。Skip(1)`。

其余的-组1和组2的值-与. Since the first group is the whole match value, we串联。