2014-05-08 50 views
-5

如何將電話號碼的格式從(###)### - ####改爲##########?有沒有最好的方法來做到這一點?我可以使用String.Substring來獲取每個數字塊,然後連接它們。但是,還有其他複雜的方法嗎?格式化電話號碼

回答

3

一個簡單的正則表達式替換如何?

string formatted = Regex.Replace(phoneNumberString, "[^0-9]", ""); 

這實質上只是一個白色的數字列表。看到此小提琴:http://dotnetfiddle.net/ssdWSd

輸入:(123)456-7890

輸出:1234567890

+0

'+'是不必要的,因爲函數將查找滿足指定的正則表達式的所有子字符串並將其替換。 – wei2912

+0

@ wei2912你是對的,修好了。 – tnw

0

一個簡單的方法是:

myString = myString.Replace("(", ""); 
myString = myString.Replace(")", ""); 
myString = myString.Replace("-", ""); 

用一個空字符串替換每個字符。

+2

這不會工作,因爲它假定字符串是可變的,他們不是。 –

+0

我總是忘記這一點。我的編輯工作? – dckuehn

+0

現在它會工作。 -1不是我的。 –

-1

嘗試這種情況:

​​

REGEX說明

^\((\d+)\)(\d+)-(\d+)$ 

Assert position at the beginning of the string «^» 
Match the character 「(」 literally «\(» 
Match the regex below and capture its match into backreference number 1 «(\d+)» 
    Match a single character that is a 「digit」 (0–9 in any Unicode script) «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Match the character 「)」 literally «\)» 
Match the regex below and capture its match into backreference number 2 «(\d+)» 
    Match a single character that is a 「digit」 (0–9 in any Unicode script) «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Match the character 「-」 literally «-» 
Match the regex below and capture its match into backreference number 3 «(\d+)» 
    Match a single character that is a 「digit」 (0–9 in any Unicode script) «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$» 

$1$2$3 

Insert the text that was last matched by capturing group number 1 «$1» 
Insert the text that was last matched by capturing group number 2 «$2» 
Insert the text that was last matched by capturing group number 3 «$3» 
+1

謹慎解釋倒票? –

3

我會使用LINQ做到這一點:

var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray()); 

雖然正則表達式也適用,這並不需要任何特殊設置。