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

I made the following regular expression:

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

And it works. That is, it will correspond to a 5-digit number or 5-digit number, it has only 1 hyphen, but the hyphen cannot be a line or an end.

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

Can anyone suggest a simpler regex?

Additional notes: I put this regular expression in an XML file that should be used by an ASP.NET application. I do not have access to .net code. But I suspect they will do something:

 Match match = Regex.Match("Something goes here", "my regex", RegexOptions.None); 
+4
source share
5 answers

You need to use lookahead:

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

Explanation:

  • Or it \d{25} from beginning to end, 25 digits.
  • Or: it's 26 characters [\d\-] (numbers or hyphens) AND it matches \d+-\d+ - this means that it has exactly one hyphen in the middle.

Regular expression visualization

Working example with test cases

+10
source

You can use this regex:

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

The caretaker guarantees only 1 dash, and the character class ensures that there will be 23 numbers between the first and last. Perhaps I will make it shorter, although I think.

EDIT: bit is shorter than xP

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

A bit like Kobe, though, I admit.

+5
source

If you don’t bother about length at all (i.e. you only need a string of numbers with an optional hyphen), you can use:

 ([\d]+-[\d]+){1}|\d 

(You can add line / word boundaries to this, depending on your circumstances)

If you need a specific match length, this pattern really doesn't work. Kobe's answer is probably best for you.

0
source

I think the fastest way is to make a simple match, and then add the length of the capture buffers, why trying a math in a regex does nothing.

  ^(\d+)-?(\d+)$ 
0
source

This will correspond to 25 digits and exactly one hyphen in the middle:

 ^(?=(-*\d){25})\d.{24}\d$ 
0
source

Source: https://habr.com/ru/post/1498470/


All Articles