Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Everyone,

Can anyone please provide me the regex format for the below.

XXXXXXXXX,
XX-XXXXXXX
XXX-XX-XXXX

What I have tried:

i tried the below 
<pre>string pattern1= @"\d{9}|\d{3}-\d{2}-\d{4}|\d{3}-\d{6}|\d{5}-\d{4}";

string pattern2 = @"[1-9]\d{8}|[1-9]\d?-\d{7}";
Posted
Updated 13-Mar-19 1:56am

Quote:
\d{9}|\d{3}-\d{2}-\d{4}|\d{3}-\d{6}|\d{5}-\d{4}

What is the problem with that regEx?
Advice: use the Debuggex to see a nice graph and test your data.

Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 
v2
First off, make up your mind what language you are using: a JS solution will not be identical to a Java or C# solution.

Assuming C#, your expression works fine:
string pattern1 = @"\d{9}|\d{3}-\d{2}-\d{4}|\d{3}-\d{6}|\d{5}-\d{4}";
Regex reg = new Regex(pattern1);
if (reg.IsMatch("123456789")) Console.WriteLine("9 OK");
if (reg.IsMatch("123-45-6789")) Console.WriteLine("3-2-4 OK");
if (reg.IsMatch("123-456789")) Console.WriteLine("3-6 OK");
if (reg.IsMatch("12345-6789")) Console.WriteLine("5-4 OK");
Gives:
9 OK
3-2-4 OK
3-6 OK
5-4 OK
The only difference I would make is to add start and end of line characters:
string pattern1 = @"^\d{9}|\d{3}-\d{2}-\d{4}|\d{3}-\d{6}|\d{5}-\d{4}$";
Regex reg = new Regex(pattern1);
So what's the problem with it?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900