I try to extract 7 numbers (a contract number) out of a random string using regex:

pattern contractNumberPattern = pattern.compile('[0-9]{7}'); 
Matcher contractNumberMatcher = contractNumberPattern.matcher('Test1234567Test');   
String contractNumber;
contractNumber = contractNumberMatcher.group(0);

Unfortunately this does not bring the desired result. the find() returns true but the groups are empty.

I tested my regex on a regex tester site and it bringt the right result. So ... where am I wrong?

Thanks and best, Markus

1 Answer 1


Your Pattern and Matcher are fine, assuming you only ever want the first 7 numeric values in a String. The problem (even at compile time) is coming from your call to matches() in which the system class is looking to match an entire region, in your case find() is good enough. The following returns the first 7 numeric values, you can extend the length of such value by modifying the {7} parameter in the regex or can simply use + if you pre-validate the Contract numeric value length.

Pattern pat = Pattern.compile('([0-9]{7})');
Matcher matcher = pat.matcher('Test12345678Test');
Boolean matches = matcher.find();

An alternative to using Patterns and Matchers, you can do some String manipulation with a classical for loop.

String contractNumber = 'Test12345678Test';
String numericString = '';
for(Integer i=0; i<contractNumber.length(); i++) {
    String character = contractNumber.mid(i, 1);
    if(character.isNumeric()) {
        numericString += character;
System.debug('Contract number is: ' + numericString);
  • Thanks a lot ... by doing too many system.debugs I prevented it from working *sigh
    – Markus
    Feb 10, 2021 at 13:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .