using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(?:(4\d{3}(?P<DelimVI>[\ \-]?)(?:\d{4}(?P=DelimVI)){2}\d(?:\d{3})?)|(5([1-5]\d{2})(?P<DelimMC>[\ \-]?)\d{4}(?P=DelimMC)\d{4}(?P=DelimMC)\d{4})|(3[47]\d\d(?P<DelimAX>[\ \-]?)\d{6}(?P=DelimAX)\d{5}))";
string input = @"""This is Visa number 4111111111111111, next is MasterCard number 5105105105105100, next is Amex 378282246310005""
//Visa 13 or 16 digits with optional delimiters of spaces or dashes between number groups, e.g.“4012-8888-8888-1881” or “4012-8888-8888-1”.
""//Master 16 digits with optional delimiters of spaces or dashes between number groups, e.g.“5112-8888-8888-1881”
//American Express with optional matching delimiters of spaces or dashes between number groups, e.g. “3714-496353-98431” or “3714 496353 98431”, but not mix of delimeters “3714-496353 98431” .
(4\d{3}(?P<DELIM>[\ \-]?)(?:\d{4}(?P=DELIM)){2}\d(?:\d{3})?)
(?:(4\d{3}(?P<DelimVI>[\ \-]?)(?:\d{4}(?P=DelimVI)){2}\d(?:\d{3})?)|(5([1-5]\d{2})(?P<DelimMC>[\ \-]?)\d{4}(?P=DelimMC)\d{4}(?P=DelimMC)\d{4})|(3[47]\d\d(?P<DelimAX>[\ \-]?)\d{6}(?P=DelimAX)\d{5}))";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for C#, please visit: https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v=vs.110).aspx