c# - 正则表达式从字符串中精确匹配 11 位电话号码并从 C# 中的匹配中删除连字符(-)
问题描述
我正在 c# windows 窗体中创建一个文本解析器,我想用-分隔符识别从 0 开始的 11 位电话号码,例如 0341-2239548 或 021-34223311 应使用 Regex.Match 分别转换为 03412239548 和 02134223311。我找不到相关的正则表达式,有人可以帮我吗?
string[] RemoveCharacter = { "\"", "(", ")", "/=", "/", ":-", ":", ";", "-" };
foreach (string word in RemoveCharacter)
{
s = s.Replace(word, " ");
}
删除这些字符后,电话号码也用空格分隔,我不希望这种情况只发生在电话号码上。
解决方案
您可以使用下面的正则表达式从电话号码中删除所有连字符和所有其他非数字字符
string pattern = @"\b([\-]?\d[\-]?){11}\b";
Regex rgx = new Regex(pattern);
var sentence = "This is phone number 0341-2239548 and 021-34223311";
var matches = rgx.Matches(sentence);
foreach (Match match in matches)
{
string replacedValue = Regex.Replace(match.Value, @"[^0-9]", "");
sentence = sentence.Replace(match.Value, replacedValue);
}
查看演示
推荐阅读
- android - 与许多设备的蓝牙连接
- intellij-idea - Intellij 本地历史“贴标签”有什么意义?
- django - Nginx 502 网关错误 - gcp
- typescript - 如何查看来自 TypeScript 插件的日志?
- sql - SQL连接两个表并从两个表中删除重复项,但不会丢失表本身的任何重复项
- javascript - 部署到 Heroku 时如何使 api 端点以用户的本地主机为目标
- android - 如何添加重新发送otp firebase android的代码
- java - 无法理解输出顺序,使用 Scanner 和 FileReader 读取文本文件并打印
- python - While循环不会改变索引
- python - ResNeSt 问题:load_state_dict_from_url() 得到了一个意外的关键字参数“check_hash”