0

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;
system.debug(contractNumberMatcher.find());
system.debug(contractNumberMatcher.matches());
system.debug(contractNumberMatcher.groupCount());
system.debug(contractNumberMatcher.group());
contractNumber = contractNumberMatcher.group(0);
system.debug(contractNumber);

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

0

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();
System.debug(matcher.group(0));

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);
1
  • Thanks a lot ... by doing too many system.debugs I prevented it from working *sigh
    – Markus
    Feb 10, 2021 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.