There are some mobile number, 11 digits in total, such as 15213131313,12856565656... It looks like ***abababab. How to use regex pattern to get these number from all mobile number which has 11-digit in total in c#?
You are looking for a back reference
http://www.regular-expressions.info/backref.html
C# implementation:
using System.Text.RegularExpressions;
...
string source = "15213131313";
// .* - any symbols
// (?<a>[0-9]) - digit "a" group
// (?<b>[0-9]) - digit "b" group
// (\k<a>\k<b>){3} - ababab - "a" and "b" repeated three times
string pattern = @"^.*(?<a>[0-9])(?<b>[0-9])(\k<a>\k<b>){3}$";
if (Regex.IsMatch(source, pattern)) {
Console.WriteLine("***abababab");
}
More strict pattern (we insist on exactly 11-digit mobile number format)
// ^ - achor, string start
// [0-9]{3} - exactly three digits
// (?<a>[0-9]) - digit "a" group
// (?<b>[0-9]) - digit "b" group
// (\k<a>\k<b>){3} - ababab - "a" and "b" repeated three times
// $ - anchor, string end
string pattern = "^[0-9]{3}(?<a>[0-9])(?<b>[0-9])(\k<a>\k<b>){3}$";