Home > Net >  Regex pattern infinite number of times except last one different
Regex pattern infinite number of times except last one different

Time:11-13

I'm trying to build a regex to check if a text input is valid. The pattern is [NumberBetween1And999]['x'][NumberBetween1And999][','][White space Optional] repeated infinite times.

I need this to make an order from a string: the first number is the product id and the second number is the quantity for the product.

Examples: of good texts:

1x1
2x1,3x1
1x3, 4x1

Should not catch:

1x1,
1,1, 1x1,
9999x1
1x1,99999x1

I'm blocked there: ^(([1-9][0-9]{0,2})x([1-9][0-9]{0,2}),)*$

Thanks for helping me

CodePudding user response:

You can use

^[1-9][0-9]{0,2}x[1-9][0-9]{0,2}(?:,\s*[1-9][0-9]{0,2}x[1-9][0-9]{0,2})*$

The pattern matches:

  • ^ Start of string
  • [1-9][0-9]{0,2}x[1-9][0-9]{0,2} Match a digit 1-9 and 2 optional digits 0-9, then x and again the digits part
  • (?: Non capture group to repeat as a whole
    • ,\s* Match a comma and optional whitespace char
    • [1-9][0-9]{0,2}x[1-9][0-9]{0,2} Match the same pattern as at the beginning
  • )* Close the non capture group and optionally repeat it to also match a single part without a comma
  • $ End of string

Regex demo

  • Related