Blog

Extract product codes from multiple lines with a regular expression

Extract only lines containing SKU- followed by four digits. Screenshots show how the browser regex tester uses m for line boundaries, g to find all matches, and offsets to identify each match’s start.

English regex tester showing SKU-0142 and SKU-0261 extracted from a list of product codes.

An inventory list mixes current product codes with older formats. The codes wanted here contain only the ASCII prefix SKU- followed by four digits on a line. Use the Regex tester to check that lines with too few digits or a trailing note are excluded.

Find lines containing only a product code

Paste this fictional list into Input text.

SKU-0142
SKU-7
SKU-0188-old
SKU-0261
  1. Enter ^SKU-[0-9]{4}$ in Pattern. Do not include the slashes that sometimes surround a regular expression.
  2. Enter gm in Flags. With m, ^ and $ also match the start and end of each line. The g flag searches for successive matches from the beginning.
  3. Press Run test. Result shows SKU-0142 and SKU-0261. SKU-7 has only one digit, and SKU-0188-old does not end immediately after the four digits, so neither matches.
English interface with flags gm and two results: SKU-0142 and SKU-0261.
Enter the pattern and flags in separate fields. The results show each matching code and its starting position.

The result labels [0] and [1] are the match numbers, counted from zero. The number after @ is the starting position, measured from zero at the beginning of the entire input. The second match’s @28 means the code starts 28 positions into the input, including line breaks. Positions use JavaScript UTF-16 code units; for example, the emoji 📦 takes two units.

Remove flags and compare the results

Remove only g and run with m: only the first match, SKU-0142, appears. Restore gm to see subsequent matches. Conversely, removing only m leaves g; ^ and $ then refer to the ends of the entire input, so this four-line example has no matches.

English interface running with the flag m and showing only the first code, SKU-0142.
Keeping m and removing g ends the search after the first match.

Extraction leaves the original text unchanged. Select and copy the extracted text from the result field. Long lists are limited to 2,000 displayed matches, and output also stops at the result character limit. If a truncation message appears, split the list and check each part separately. The tool uses the browser’s JavaScript regular expressions. When reusing the same pattern in another language or editor, check which syntax and flags that environment supports.