C# 正则表达式用于拆分除序数指示符外的数字和字符串

C# 正则表达式用于拆分除序数指示符外的数字和字符串,c#,regex,C#,Regex,寻找一个正则表达式来引入一个空间,其中数字和字符串在用户输入中连接,顺序指示符除外,例如1、11、22、33、44等 所以这个字符串: 您好,12月18日至21日有空吗 返回为 嗨,12月18日至21日有空吗 使用这个表达式 Regex.Replace(value, @"(\d)(\p{L})", "$1 $2")) 给予 您好,12月18日至21日有空吗 编辑: 根据@juharr dec12th的评论,应改为12月12日,您可以使用如下解决方案: var s = "Hi is this

寻找一个正则表达式来引入一个空间,其中数字和字符串在用户输入中连接,顺序指示符除外,例如1、11、22、33、44等

所以这个字符串:

您好,12月18日至21日有空吗

返回为

嗨,12月18日至21日有空吗

使用这个表达式

 Regex.Replace(value, @"(\d)(\p{L})", "$1 $2"))
给予

您好,12月18日至21日有空吗

编辑:


根据@juharr dec12th的评论,应改为12月12日,您可以使用如下解决方案:

var s = "Hi is this available 18dec to 21st dec 2nd dec 1st jan dec12th";
var res = Regex.Replace(s, @"(\p{L})?(\d+)(st|[nr]d|th|(\p{L}+))", repl);
Console.WriteLine(res);
// => Hi is this available 18 dec to 21st dec 2nd dec 1st jan dec 12th

// This is the callback method that does all the work
public static string repl(Match m) 
{
    var res = new StringBuilder();
    res.Append(m.Groups[1].Value);  // Add what was matched in Group 1
    if (m.Groups[1].Success)        // If it matched at all...
        res.Append(" ");            // Append a space to separate word from number
    res.Append(m.Groups[2].Value);  // Add Group 2 value (number)
    if (m.Groups[4].Success)        // If there is a word (not st/th/rd/nd suffix)...
        res.Append(" ");            // Add a space to separate the number from the word
    res.Append(m.Groups[3]);         // Add what was captured in Group 3
    return res.ToString();
}

使用的正则表达式是

(\p{L})?(\d+)(st|[nr]d|th|(\p{L}+))
看。它匹配:

  • (\p{L})
    -与单个字母匹配的可选组1
  • (\d+)
    -第2组:一个或多个数字
  • (st |[nr]d | th |(\p{L}+)
    -第3组匹配以下备选方案
    • st
      -
      st
    • [nr]d
      -
      nd
      rd
    • th
      -
      th
    • (\p{L}+)
      -第4组:任意一个或多个Unicode字母
repl
回调方法获取match对象,并根据可选组是否匹配,使用附加逻辑来构建正确的替换字符串


如果需要不区分大小写的搜索和替换,请传递
RegexOptions.IgnoreCase
选项;如果只想将ASCII数字与
\d
匹配,请传递
RegexOptions.ECMAScript
(请注意,
\p{L}
仍将匹配任何Unicode字母,即使将此选项传递给regex)。

并且您需要“dec12”改为“12月12日”,对吗?@juharrCorrect@MatthewEvans那么请将此要求添加到问题中。@WiktorStribiżew-已经这样做了。这确实让问题变得更加困难,我将更新代码。@MatthewEvans,但您有足够的时间提出其他问题。见juharr在问题下的评论。