.Net正则表达式在字符串中查找信用卡号

时间:2015-05-20 19:22:27

标签: c# regex

有人知道在C#中如何在字符串中查找信用卡号。 我想阻止用户在我们的应用程序的评论部分输入CC#并向用户发出警告

我在互联网上搜索的所有正则表达式只有在字符串包含信用卡号(“12345678910”)

时才有效

例如

string comment =“客户致电并提供了他的信用卡号码12345678910.I将为客户下订单”

在这种情况下,我想让用户知道此评论无法保存,因为它包含信用卡号

这是我拥有且无法使用的示例代码

public class CreditCardValidator
    {
        public CreditCardValidator()
        {
            //These are the regex for all the avialble Credit  cards.http://www.regular-expressions.info/creditcard.html

            this.Patterns = new string[] { "^4[0-9]{12}(?:[0-9]{3})?$", "^5[1-5][0-9]{14}$", "^3[47][0-9]{13}$", "^3(?:0[0-5]|[68][0-9])[0-9]{11}$", "^6(?:011|5[0-9]{2})[0-9]{12}$","^(?:2131|1800|35\\d{3})\\d{11}$" };
        }
        public string[] Patterns { get; set; }
        public  bool HasCreditCardNumber(string input)
        {
            foreach (var pattern in Patterns)
            {
                if (Regex.IsMatch(input, pattern, RegexOptions.Multiline))
                {
                    return true;
                }                   
            }

            return false;
        }
    }

感谢您的帮助

4 个答案:

答案 0 :(得分:2)

只需删除开头的^和每个正则表达式模式末尾的$即可。这些说"必须以" /"必须以"结束。即使使用多行选项,行也是如此。

我猜这些正则表达式模式与输入信用卡号完全匹配。但不会为文本搜索工作。

答案 1 :(得分:1)

我最终做出了这一改变,似乎正在发挥作用。为了您的反馈,我们全力以赴。

// string comment = @"这是我的信用卡4418831001112089.Please for order&#34 ;;

public static bool HasCreditCardNumber(string input)
    {
        MatchCollection matches = Regex.Matches(input, @"\b4[0-9]{12}(?:[0-9]{3})?\b|\b5[1-5][0-9]{14}\b|\b3[47][0-9]{13}\b|\b3(?:0[0-5]|[68][0-9])[0-9]{11}\b|\b6(?:011|5[0-9]{2})[0-9]{12}\b|\b(?:2131|1800|35\d{3})\d{11}\b");
        if (matches.Count > 0)
        {
            return true;
        }            
        return false;
    }

答案 2 :(得分:0)

包括正则表达式。然后当你失去对盒子的焦点然后引发错误(通过警告(丑陋)或通过使表单无效或显示说明这是无效的说明因为......)并且不要让用户提交表单。这不是C#自动执行的操作。你可以等到点击事件来验证它....但我会马上做。

答案 3 :(得分:0)

使用信用卡匹配表达式,但对其执行否定断言。这将触发任何客户端验证,它应该即插即用。