我是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);
所以最终结果看起来像
第四大道还有一些话
答案 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} },nd
或rd
作为整个单词(因为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
串联。