How do I use regular expressions in Apex to extract data from a string?

Assuming an input string is a well formed duration in the form “1hr 30m”, how can I get the 1 and 30 out and into their own variables?

Answer

Prep work

  1. Build the regular expression (there’s lots of web resources on that, but use the Java versions as that’s what Apex does under the hood). Eg. \d+h \d+m

  2. Use braces to define the parts you’re interested in. (\d+)h (\d+)m

  3. Turn it into a string by escaping any backslashes '(\\d+)h (\\d+)m'

Write the code

  1. Create a Pattern object using your string

  2. Use that to create a Matcher object.

  3. Test to see if you got any matches using the Matcher’s matches() function.

  4. If you did, you can get the matches from the Matcher’s group() function.

    Pattern p = Pattern.compile('(\\d+)h (\\d+)m');
    Matcher pm = p.matcher( yourString );
    
    if( pm.matches() ){
         hours = pm.group(1);
         minutes = pm.group(2);
    }
    

I’ll leave it to you to declare hours and minutes, give them defaults, and to cast them into numerical types if you don’t want them as strings.

You can, of course, chain the methods:

    Matcher pm = Pattern.compile('(\\d+)h (\\d+)m').matcher( yourString );

but if you’re doing it more than once, you’re recompiling the regular expression over and over.

Attribution
Source : Link , Question Author : RickMeasham , Answer Author : David Gillen

Leave a Comment