Removing unwanted matches from regex expression

Viewed 49

I have a list of strings like:

  • Missing image 09
  • Missing image 08; P012V004-0061-01 crop again
  • P012CR0409F1-1-04, P012CR0409F1-1-05 crop again
  • P012CR0602F1-2-01 crop again

Right now my regex expression for isolating image codes that need cropping looks like ([\w\d-]+)(?=.+crop again), which works but returns "Missing", "image" and "08" in the mixed cases. How can I exclude that from the results? I'm guessing lookahead/behind again but can't get it to work. A bonus would be to return the missing images in another group since I'll need them too.

Many thanks,

2 Answers

You may use

[\w-]+(?=(?:\s*,\s*[\w-]+)*\s+crop again)

See the regex demo

Here,

  • [\w-]+ - matches 1 or more letters, digits, underscores or hyphens
  • (?=(?:\s*,\s*[\w-]+)*\s+crop again) - that are followed with
    • (?:\s*,\s*[\w-]+)* - 0 or more repetitions of a comma enclosed with whitespaces and then 1+ word/- chars
    • \s+ - 1+ whitespaces and then
    • crop again - literal substring.

Assuming image codes always follow the format like

  • P012V004-0061-01
  • P012CR0409F1-1-04
  • P012CR0409F1-1-05
  • P012CR0602F1-2-01

i.e. an alphanumeric combination of variable length, then a hyphen, then a number, then a hyphen, then a number.

You could do:

[a-zA-Z0-9]+-[0-9]+-[0-9]+
Related