Match a sequence for detecting ingredient brand in regex

Viewed 40

By capturing the following pattern ; AAA-AAA it is possible to detect an ingredient brand. It's a semi colon, a space (only one), three letter or number combination, a hyphen and three letter or number combination.

For example in this string: "Bakery: Desdemona (Desserts; A9B-APO) 7th Avenue" the ingredient is A9B-APO

A can be a number or a letter. I tried unsuccessfully to write a regex:

"^w(;s[a-zA-Z][a-zA-Z][a-zA-Z]-[a-zA-Z][a-zA-Z][a-zA-Z])

Please, could you help me with this expression? Thank you.

1 Answers

You can use

;\s([a-zA-Z0-9]{3}-[a-zA-Z0-9]{3})\b

See the regex demo.

Details

  • ; - a semi-colon
  • \s - one whitespaces
  • ([a-zA-Z0-9]{3}-[a-zA-Z0-9]{3}) - Capturing group 1 (your value is here): three alphanumeric, - and three alphanumeric chars
  • \b - a word boundary.

If the number of alphanumeric chars can be any, starting with one, you may use ;\s([a-zA-Z0-9]+-[a-zA-Z0-9]+)\b, where {3} is replaced with the + quantifier.

Related