I need a regex in C# for below mentioned number
31–00–123456–000–0001
I am having a problem putting the dash in the regex. The number validation is pretty fine.
I need a regex in C# for below mentioned number
31–00–123456–000–0001
I am having a problem putting the dash in the regex. The number validation is pretty fine.
Is this what you need?
(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})
So, if you already have code extracted to string variable code and want to check that it matches then use ^ and $ like here:
^(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})$
According to comments, its better to use [0-9] to reduce other types of degets.
^([0-9]{2})[\–\-]([0-9]{2})[\–\-]([0-9]{6})[\–\-]([0-9]{3})[\–\-]([0-9]{4})$
If any kind of dash (e.g. U+02013
) are acceptable, I suggest using \p{Pd}
which means any unicode dash (Punctuation dash). In case the digits should be separated by any dash, which, however, must be the same within the entire string:
Regex regex = new Regex(@"^[0-9]{2}(\p{Pd})[0-9]{2}\1[0-9]{6}\1[0-9]{3}\1[0-9]{4}$");
Demo:
string[] tests = new string[] {
"31–00–123456–000–0001", // All Dashes
"31-00-123456-000-0001", // All minuses
"31–00-123456-000-0001", // Dash then minues
};
string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,25} :: {(regex.IsMatch(test) ? "Matched" : "Failed")}"));
Console.Write(report);
Outcome:
31–00–123456–000–0001 :: Matched
31-00-123456-000-0001 :: Matched
31–00-123456-000-0001 :: Failed
If you want to tolerate diffrent dashes within the same string:
Regex regex = new Regex(
@"^[0-9]{2}\p{Pd}[0-9]{2}\p{Pd}[0-9]{6}\p{Pd}[0-9]{3}\p{Pd}[0-9]{4}$");