2013-09-24 32 views
0

嗨我有一個C#應用程序,它接受一個4位數的分機號碼,併爲它設置一個掩碼。我有兩種不同的口罩需要使用,具體取決於數量。正則表達式模式來區分四位數字

First: If the number starts with 47 or 5 return mask A. 

Second: If the number starts with 6 or 55 return mask B. 

所以我設置我的正則表達式這種方式,我不知道爲什麼它設置錯誤。

//Here I am trying to say, anything that start with 47 or 5 with the next 3 digits taking any number 
Match first = Regex.Match(num, "^(47|(5[]{3}))"); 

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5 
Match secong = Regex.Match(num, "(6|55[123450]{2})"); 

如果我給使用上面輸入NUM = 5850或num = 5511這將是雙方真實的,但顯然5850應該使用面膜A和5511應該使用掩模B

我該如何解決這個問題??

謝謝!

+1

開始測試6或55第一,如果失敗,將檢查47或5 – Jerry

+1

你絕對要做到這一點的一個正則表達式而不是添加一堆'if(input.StartsWith(「47」)){...}'子句? – millimoose

+0

你可以移動你的兩個比賽的位置,使它匹配55之前,它會嘗試匹配5? – Andrew

回答

1

這些應該爲你做。

這匹配任何以47或5開頭的4位數字,不包括5作爲第二位數字。

^(47|5([0-4]|[6-9]))\d{2}$ 

這符合先從6或55

^(6\d|55)\d{2}$ 
+0

謝謝你做了我想要的! – laitha0

+0

你的問題陳述「如果數字以6或55返回掩碼B開始」,但在稍後的正則表達式中,你會聲明「6或55,接下來的兩位數字取0-5」。我知道你已經接受了,但是可以請你說好嗎?最後兩位數字應該是什麼,或者只是0-5? – Syon

+0

他們應該只需要0-5,因爲我們沒有擴展名,最後兩位數字是任意數字......但這不是問題,因爲它無論如何都不會嘗試輸入它們 – laitha0

0

看起來你應該使用4個正則表達式

/^47\d{3}/ 

/^5\d{4}/ 

/^6\d{4}/ 

/^55\d{3}/ 

通知與55開頭的數字是如何爲您的兩個案件的比賽,但是反過來不適合與5開頭的數字,你的工作應使用事實


區分它們,如果你想正則表達式相結合,比這很好

/(^47\d{3})|(^5\d{4})/ 

注意:您可能還想要使用輸入錨定符的結尾:$或字邊界或負向預見匹配輸出的結尾。

1

任意4位數字,我認爲這會掩護你。請注意,您可以使用\ d爲0-9,範圍爲0-5,並且您將邊界指示符(^)從第二個邊界指示符中刪除。注意我沒有使用範圍或\ d作爲第一部分的第一部分,因爲您不想匹配55.還要注意分組。

//anything that start with 47 or 5 with the next 3 digits taking any number (but not 55!) 
Match first = Regex.Match(num, "^((47|5[])\d{2})"); 

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5 
Match secong = Regex.Match(num, "^((6|55)[0-5]{2})"); 
2

考慮以下...

Match first = Regex.Match(num, "^(47[0-9]{2}|5[0-9-[5]]{1}[0-9]{2})"); 

Match second = Regex.Match(num, "^(6[0-9]{3}|55[0-9]{2})");