[英]regex to exact match 11 digit phone number from string and remove hyphen(-) from match in 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);
}
看演示
如果您有這樣的字符串,只需刪除您的分隔符。 您不需要正則表達式:
string nr = "0154-1452146";
nr = nr.Replace("-", "");
Console.WriteLine(nr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.