. net正则表达式在字符串中查找信用卡号码
本文关键字:查找 信用卡 号码 字符串 正则表达式 net | 更新日期: 2023-09-27 17:50:14
有人知道c#中如何在字符串中查找信用卡号码吗?我想阻止用户在我们的应用程序的评论部分输入一个CC#,并给用户一个警告
我在互联网上搜索的所有Regexes只有在字符串包含信用卡号码("12345678910")时才有效
例子string comment ="客户来电并提供了他的信用卡号码12345678910。我将为客户下订单"
在这个例子中,我想让用户知道这个评论不能保存,因为它包含一个信用卡号码
这是我的示例代码,不能工作
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;
}
}
感谢您的帮助
只需删除开头的^
和每个正则表达式模式末尾的$
,它就可以工作了。它们表示"必须以"开始/"必须以"结束。即使使用多行选项,对于行也是如此。
我猜这些正则表达式模式是为了准确匹配输入到信用卡号码。但是不能用于文本搜索
我最终做了这个改变,似乎是工作。谢谢大家的反馈
//string comment = @"这是我的信用卡4418831001112089。请帮我订货吧!"
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;
}
包含正则表达式。然后,当您失去对框的关注时,就会引发一个错误(通过警告(丑陋)或通过使表单无效或显示提示说这是无效的,因为……),并且不让用户提交表单。这并不是c#可以自动完成的。您可以等到click事件来验证它....但是我会马上做的。
使用信用卡匹配表达式,但对其进行否定断言。这将触发任何客户端验证,它应该是即插即用的。