-2

I need a regex to find all the strings containing between 5-8 digits and at least 1 occurences of '_' or more. This is an example :

123456_123456 --> YES
12345678_12345678_12345678 --> YES
123456_12345678_123456_12345678 --> YES
12345_123456_1234567_12345678_ --> YES

123456_1 --> NO
123456_12 --> NO
123456_1594126781 --> NO (timestamp at the end)
123_1594126781 --> NO (timestamp at the end)

Thanks for your help !

2 Answers2

3

You may also try:

^(?:\d{5,8}_)+\d{5,8}_?$

Explanation of the above regex:

  • ^, $ - Represents start and end of line respectively.
  • (?:\d{5,8}_)+ - Represents non-capturing group matching digits 5 to 8 times along with an _ and the whole pattern repeats one or more time.
  • \d{5,8}_? - Matches digits 5 to 8 times with an optional _.

enter image description here

Regex Demo

2

The trailing _ on the 4th valid sample seems a bit strange. I'm assuming you'd only ever want that on the very end. Therefor a pattern like the following may work for you:

^(?=.*_)\d{5,8}(?:_\d{5,8})*_?$

See the online demo here.

Note that this would also validate 12345_ since it would have "at least 1 occurences of '_' or more.". If that is not what you meant you could change the * quantifier into a + and remove the positive lookahead:

^\d{5,8}(?:_\d{5,8})+_?$

See the online demo here

JvdV
  • 41,931
  • 5
  • 24
  • 46
  • Thanks a lot for your 2 solutions ! My tries was far away from your solution... I'm going to use your second approach to be sure my specific code is not executed for "12345_". Thanks again, Regex is not my strong suit... – Jonathan RIO Jul 08 '20 at 13:43