using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(?<!\d[ _-])(?<!\d)\d{4}(?:[_ -]?\d{4}){3}(?![_ -]?\d)";
string input = @"1234123412341234
(16 digits all together)
1234 1234 1234 1234
1234-1234-1234-1234
(card numbers with hyphens and spaces)
Find me 1234-1234-1234-1234 Find me (card numbers hidden amongst text)
What I'm struggling to stop is the false positives I get, which I know are a direct result of achieving result number 4 above. The false positives being more than 16 digits which are clearly not card numbers. E.g
1) 1234-1234-1234-1234-1234";
RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace;
foreach (Match m in Regex.Matches(input, pattern, options))
{
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