首页 > 解决方案 > 正则表达式从字符串中精确匹配 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, " ");
        }

删除这些字符后,电话号码也用空格分隔,我不希望这种情况只发生在电话号码上。

标签: c#.netregexwinforms

解决方案


您可以使用下面的正则表达式从电话号码中删除所有连字符和所有其他非数字字符

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);
}

查看演示


推荐阅读