Skip to main content
 首页 » 编程设计

c#之使用正则表达式在 5 位数字后的 9 位数字中插入连字符

2024年01月29日22jyk

我必须在 c# 中的文本更改事件中自动插入 9 位数字中的连字符,而 javascript 除外。

所以如果我的号码是 123456789 那么它会自动变成 12345-6789。

我想使用 regex.match。

我的尝试:

正则表达式 "^\d{5}(-\d{4})?$"是结果应该的样子。

所以,

Regex regTest = new Regex("^\\d{5}(-\\d{4})?$"); 
 
Match match = regTest.Match(s); 
 
if (match.Success) 
           { 
              var numString = match.Value; 
           } 

但是上面没有返回成功。

感谢您的帮助。

请您参考如下方法:

您的代码示例只是检查格式是否为xxxxx-xxxx。它不会插入连字符。

您不需要 RexEx 来插入连字符:

myString.Insert(5, "-");