Apex Regex Extract Numeric Value from String
You are using a capturing group so this works as you expect: (You need to use find):
Pattern pat = Pattern.compile('([0-9]+)');
Matcher matcher = pat.matcher('red fox 11133434 red fox');
Boolean matches = matcher.find();
system.debug(logginglevel.error,matches);
system.debug(logginglevel.error,matcher.group(1));
You will notice the debugs are true and 11133434
A good site to test out your regex and break it down it:
https://regex101.com
B"H
Thanks Eric for answering the question. Just for completeness I am sharing the definition difference between find
and matches
from the Java docs:
A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:
- The
matches
method attempts to match the entire input sequence against the pattern.- The
lookingAt
method attempts to match the input sequence, starting at the beginning, against the pattern.- The
find
method scans the input sequence looking for the next subsequence that matches the pattern.