繁体   English   中英

正则表达式匹配超过4个字符

[英]Regex Match more than 4 characters

我遇到了超过4个字符的Regex Match问题。 我尝试使用4个字符,它返回的结果为true 但是,对于超过4个字符,它将返回false类型 请让我知道那里发生了什么。

  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

^在字符串开头声明当前位置

$声明当前位置在字符串的末尾

由于这些是外部捕获组,因此输入的每个卡号必须匹配,这当然是有意的。 但是,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

您可能永远不会将Visa条件与可匹配的数字相匹配。 它正在尝试Visa,意识到它不匹配,回溯,跳过发现并尝试使用AmEx,然后继续进行。

编辑:我明白了。 您可能尚未意识到命名组仍在编号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM