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
- Start with Text A12
- Do this Capture the two digits
- Result 12 as text
Apply it to a real problem
- Start with Invoice references INV-007 and INV-12
- Do this Extract the named number group
- Result 007 and 12
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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"));
}
}
}
007 12