TransWikia.com

Apex Regex Extract Numeric Value from String

Salesforce Asked by Yossi Cadaner on January 6, 2022

B”H
I am unable to extract a consecutive set of numbers from within a (single line) string using ([0-9]+). However, surrounding it with match-all other does work (.*?[0-9].*). Can someone explain to me why ([0-9]+) is not working for this task.
Here’s my code:

@Test
public void testMethod(){
    Pattern pat = Pattern.compile("([0-9]+)");
    Matcher matcher = pat.matcher("red fox 11133434 red fox");
    Boolean matches = matcher.matches();
    Assert.assertTrue("find numbers within string", matches);
    Assert.assertEquals("11133434", matcher.group(1));
}

3 Answers

Here's a utility method with a corresponding test class

    /**
     * @param input string that contains any number
     *
     * @return first digits found in string, null if input blank, found no match or too large for integer
     */
    public static Integer getInteger(String input){
        if(String.isEmpty(input)){
            return null;
        }
        Matcher matcher = Pattern.compile('\d+').matcher(input);
        if(matcher.find()){
            try {
                return Integer.valueOf(matcher.group(0));
            } catch(Exception e){
                System.debug(LoggingLevel.ERROR, e);
                return null;
            }
        } else {
            return null;
        }
    }

Test

@IsTest
static void getInteger(){
    System.assertEquals(
            1234567890,
            Strings.getInteger('foo 1234567890')
    );
    System.assertEquals(
            200,
            Strings.getInteger('-200')
    );
    System.assertEquals(
            1234567890,
            Strings.getInteger('1234567890 foo')
    );
    System.assertEquals(
            1234567890,
            Strings.getInteger('1234567890')
    );
    System.assertEquals(
            1234567890,
            Strings.getInteger('1234567890.321')
    );
    System.assertEquals(
            1234567890,
            Strings.getInteger('    1234567890   ')
    );
    System.assertEquals(
            1234567890,
            Strings.getInteger('baz 1234567890 foo 321')
    );
    System.assertEquals(
            null,
            Strings.getInteger('baz 1234567890123456789012345678901234567890')
    );
    System.assertEquals(
            null,
            Strings.getInteger('give potato')
    );
    System.assertEquals(
            null,
            Strings.getInteger('')
    );
    System.assertEquals(
            null,
            Strings.getInteger(null)
    );
}

Answered by dzh on January 6, 2022

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.

Answered by Yossi Cadaner on January 6, 2022

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

Answered by Eric on January 6, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP