2017-03-05 716 views
0

我遇到了超過4個字符的正則表達式匹配問題。我用4個字符嘗試過,它返回種類的真實。但是,如果超過4個字符,則返回種假。請讓我知道那裏發生了什麼。正則表達式匹配超過4個字符

public static string CardRegex = 
     @"^(?:(?<VisaDebit>4744)| 
     (?<Discover>6011)| 
     (?<Amex>3[47]\d{2}))([ -]?)(?(DinersClub)(?:\d{6}\1\d{4})|(?(Amex)(?:\d{6}\1\d{5})|(?:\d{4}\1\d{4}\1\d{4})))$"; 
public static CreditCardTypeType? GetCardTypeFromNumber(string cardNum) 
    { 
     var cardTest = new Regex(CardRegex); 

     var gc = cardTest.Match(cardNum).Groups; 

     if (gc[CreditCardTypeType.VisaDebit.ToString()].Success) 
      return CreditCardTypeType.VisaDebit; 
     if (gc[CreditCardTypeType.Discover.ToString()].Success) 
      return CreditCardTypeType.Discover; 
     return null; 
    } 

輸入:4744721015347572

(?<VisaDebit>4744) ==> return VisaDebit 
(?<VisaDebit>4744**7**) ==> return null 
+1

對不起,你的問題有點不清楚。您唯一的示例字符串是'4744721015347572',並且您的正則表達式[顯示匹配(如果使用IgnoreWhitespace標記編譯)](http://regexstorm.net/tester?p=%5e%28%3f%3a%28%3f% 3cVisaDebit%3e4744%29%7C%0D%0A ++++++++%28%3F%3cDiscover%3e6011%29%7C%0D%0A ++++++++%28%3F%3cAmex%3E3%5b47%5D%5CD%7B2%7D%29%29% 28%5B + - %5D%3F%29%28%3F%28DinersClub%29%28%3F%3A%5CD%7B6%7D%5C1%5CD%7B4%7D%29%7C%28%3F%28Amex%29 %28%3F%3A%5CD%7B6%7D%5C1%5CD%7B5%7D%29%7C%28%3F%3A%5CD%7B4%7D%5C1%5CD%7B4%7D%5C1%5CD%7B4 %7d%29%29%29%24&i = 4744721015347572&o = x)* VisaDebit *組中有'4744'。是否可以? –

回答

1

^斷言的當前位置在串

$的開始斷言的當前位置在字符串

的端

由於這些是在捕獲組之外,所輸入的每個卡號都必須匹配,這當然是有意的。但是,一個5位數的數字什麼都不匹配。

對於(?:(?<VisaDebit>4744),您正在搜索此4位數字。除了上面描述的斷言之外,你只是單獨匹配這個4位數字,這就是爲什麼47447不匹配,它基本上超過了你已經聲明字符串結尾的位置,除非你的變化之一匹配。


你有一個DinersClub條件(?(DinersClub)沒有一個相似的名稱組。我不知道這是否是故意的。


您的匹配模式開始時出現錯誤。這是你的正則表達式,不變。我只格式化它,所以你可以看到你的分支。

^ 
(?: 
    (?<VisaDebit>4744) 
| 
    (?<Discover>6011) 
| 
    (?<Amex>3[47]\d{2}) 
) 
([ -]?) 
(?(DinersClub)     # as described above, you have no DinersClub Group 
    (?:\d{6}\1\d{4}) 
| 
    (?(Amex) 
    (?:\d{6}\1\d{5})   # this is a problem similar to the analasys below 
    | 
    (?:\d{4}\1\d{4}\1\d{4}) # this is probably a problem 
) 
)$ 

問題的子模式analasys

\d{4} # this is saying any 4 digits 
\1  # this is a repetition of CG 1. Whatever it matched 
     # not any 4 digits, but 4744 
\d{4} # any 4 digits 
\1  # explained above 
\d{4} # any 4 digits 

你可能從來沒有匹配的簽證條件有可以匹配的數量。它正在嘗試維薩,意識到它不匹配,回溯,跳過發現和嘗試美國運通,並通過。

編輯:我明白了,我明白了。您可能沒有意識到命名組仍然有編號。