DRastislav
DRastislav

Reputation: 1882

Regex how to identify length of numbers

lets say i have String which starts with two letters and letters are followed with underscore and numbers

XX_333-335                  [A-Za-z]{2}_\d{3}-\d{3}`

` - this works good for me

but string can be: (this works as well)

XX_333-335;338;340-341        -^[A-Za-z]{2}_\d{3}-\d{3};|\d{3}|\d{3}-\d{3}

but how to check with regex if number length is 3 places?

XX_0333-0335;0338;340-0341 - In this example there should be no matches, because numbers have four positions not three

Is there any way how to solve it with regex?

thank you

Upvotes: 1

Views: 52

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

You can use

^[A-Za-z]{2}_\d{3}(?:-\d{3})?(?:;\s*\d{3}(?:-\d{3})?)*$

See the regex demo

Details

  • ^ - start of string
  • [A-Za-z]{2} - two ASCII letters
  • _ - an underscore
  • \d{3} - three digits
  • (?:-\d{3})? - an optional occurrence of - and three digits
  • (?:;\s*\d{3}(?:-\d{3})?)* - zero or more occurrences of a semi-colon followed with 0+ whitespaces, three digits and an optional sequence of three digits
  • $ - end of string.

Upvotes: 3

MonkeyZeus
MonkeyZeus

Reputation: 20737

This would do it:

^[A-Za-z]{2}_(?:\d{3}(?:[; -]+|$))+$

https://regex101.com/r/4ULAql/1

Upvotes: 1

Related Questions