Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for x number of digits and only one hyphen?

Tags:

regex

xml

asp.net

I made the following regex:

(\d{5}|\d-\d{4}|\d{2}-\d{3}|\d{3}-\d{2}|\d{4}-\d)

And it seems to work. That is, it will match a 5 digit number or a 5 digit number with only 1 hyphen in it, but the hyphen can not be the lead or the end.

I would like a similar regex, but for a 25 digit number. If I use the same tactic as above, the regex will be very long.

Can anyone suggest a simpler regex?

Additional Notes: I'm putting this regex into an XML file which is to be consumed by an ASP.NET application. I don't have access to the .net backend code. But I suspect they would do something liek this:

Match match = Regex.Match("Something goes here", "my regex", RegexOptions.None);
like image 940
John Avatar asked Dec 07 '22 05:12

John


2 Answers

You need to use a lookahead:

^(?:\d{25}|(?=\d+-\d+$)[\d\-]{26})$

Explanation:

  • Either it's \d{25} from start to end, 25 digits.
  • Or: it is 26 characters of [\d\-] (digits or hyphen) AND it matched \d+-\d+ - meaning it has exactly one hyphen in the middle.

Regular expression visualization

Working example with test cases

like image 174
Kobi Avatar answered Mar 05 '23 05:03

Kobi


You could use this regex:

^[0-9](?:(?=[0-9]*-[0-9]*$)[0-9-]{24}|[0-9]{23})[0-9]$

The lookahead makes sure there's only 1 dash and the character class makes sure there are 23 numbers between the first and the last. Might be made shorter though I think.

EDIT: The a 'bit' shorter xP

^(?:[0-9]{25}|(?=[^-]+-[^-]+$)[0-9-]{26})$

A bit similar to Kobi's though, I admit.

like image 39
Jerry Avatar answered Mar 05 '23 07:03

Jerry