Chahat
Chahat

Reputation: 3

Regular expression

I am trying to create regex which starts with abc,then space, and then 2 digit number which should not start with 0 and which should be less than 33, then in bracket there should be minimum 3 numbers comma separated and space between them. After that if comma then regex after abc should repeat.

For ex:

  1. abc 23(340, 223, 243)
  2. abc 3(336,455,344,880,567), 32(323,344,464)

I've tried to do it like:

  1. /^abc(\s((?!(0))\d{1,2}[(]([1-9][0-9]*[,]){2}([1-9][0-9]*[,]*)+[)])([,]*))+/g

  2. /^abc(\s((?!(0))\d{1,2}[(]([1-9][0-9]*[,]){2}(([1-9][0-9]*)[,]*)+[)])(([,]\s((?!(0))\d{1,2}[(]([1-9][0-9]*[,]){2}(([1-9][0-9]*)[,]*)+[)]))*))+/g

These expression do not include case less than 33 and these expressions also allow case like:

  1. abc 23(323,345,455),
  2. abc 23(323,345,455), 34()

which are not required.

Upvotes: 0

Views: 124

Answers (2)

hjpotter92
hjpotter92

Reputation: 80629

How about the following:

^abc\s(?:(?:[1-9]|[12][0-9]|3[0-3])\(\d+(?:,\s?\d+){2,}\))(?:,\s?(?:(?:[1-9]|[12][0-9]|3[0-3])\(\d+(?:,\s?\d+){2,}\)))*$

Tested against given 4 samples: https://regex101.com/r/pb8Ipv/2

If you want the matched groups for processing, replace (?: with (.

EDIT

Fixed issue with matching single digit numbers after abc

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

You could use repeating non capturing groups:

^abc (?:[1-9]|[12][0-9]|3[0-3])\([1-9][0-9]*(?:, ?[1-9][0-9]*){2,}\)(?:, (?:[1-9]|[12][0-9]|3[0-3])\([1-9][0-9]*(?:, ?[1-9][0-9]*){2,}\))*$
  • ^ Start of string
  • abc Match abc and space
  • (?: Non capturing group
    • [1-9]|[12][0-9]|3[0-3] Match a digit 1 - 33
  • ) Close group
  • \( Match (
  • [1-9][0-9]* Match a digit 1-9 and repeat 0+ digits 0-9
    • (?:, ?[1-9][0-9]*){2,} Match a comma, optional space and repeat 2 or more times to match a minimum of 3 numbers
  • \) Match )
  • (?: Non capturing group
    • , Match a comma and a space
    • (?:[1-9]|[12][0-9]|3[0-3])\([1-9][0-9]*(?:, ?[1-9][0-9]*){2,}\) Repeat same as first pattern
  • )* Close group and repeat 0+ times
  • $ End of string

Regex demo

Upvotes: 1

Related Questions