Regular Expressions 101

Community Patterns

Get SKU, leave out _# before file extension

0

Regular Expression
PCRE2 (PHP >=7.3)

/
^([-\w\d\.]+?)(?(?=_)|(?=\.jpg))
/
gm

Description

For a batch of photos named in the following fashion: {SKU}_{#}.jpg, where the _{#} is optional, only present when the photo is part of an image gallery for a given SKU.

This expression uses lazy quantifying, because I need the expression to match as many characters as there are leading up to the photo number or file extension. If I wouldn't use lazy quantification, the expression would capture everything and then backtrack, measuring against the lookahead, at which point it would always succeed first on the '.jpg' file extension.

However, when using a lazy quantifier, the engine will match a character and check the lookahead before matching the next character. That way, if there is an underscore in the file name, the expression will match and return.

Submitted by Mendel Groner - 2 years ago