Extract invoice numbers with a named group in Java

Scan several invoice references in one string. A named group isolates the digits and preserves leading zeros for display.

A simple example

Capture the two digits

  1. Start with Text A12
  2. Do this Capture the two digits
  3. Result 12 as text
A capture returns the characters matched by its part of the pattern.

Apply it to a real problem

  1. Start with Invoice references INV-007 and INV-12
  2. Do this Extract the named number group
  3. Result 007 and 12
Keeping each capture as text preserves the leading zeros.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws Exception {
        var invoice = Pattern.compile("INV-(?<number>[0-9]+)");
        var match = invoice.matcher("INV-007, paid; INV-12, pending");
        while (match.find()) {
            System.out.println(match.group("number"));
        }
    }
}
Output
007
12

Official Java documentation