Search code examples
regexregex-group

Regex validate this string


Suppose I want to validate request

item-dsaK123 - request
item-dsaK123*item-Dslw123 - request
item-dsaK123*item-Dslw123*item-ABcd123 - request
item-dsaK132*item-Ddsw532 - request

How can I validate those strings:

  • no empty string
  • each item must start with item with dash in the middle and unique identifier consist of a-z, A-Z, digit in random order.
  • each item can be concatenated to show relationship but it is separated by "*".

valid:

item-dsaK123 
item-dsaK123*item-Dslw123 
item-dsaK123*item-Dslw123*item-ABcd123 
item-dsaK132*item-Ddsw532 

invalid:

item-dsaK132+item-Ddsw532*item-ABcd123 
item-dsaK132+
""(empty string)

Solution

  • You could use this regex, which matches a string containing an item, followed by 0 or more of * followed by another item:

    ^item-[a-zA-Z0-9]+(?:\*item-[a-zA-Z0-9]+)*\s?$
    

    Demo on regex101

    Note I've put a trailing \s? on the regex because some of the strings in the question data end with a space. If that's not the case IRL, you can remove it from the regex.