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?
Attribution to: RickMeasham
Possible Suggestion/Solution #1
Here is a slight improvement on this that will return just the hour and minute digits without the preceding 'hr' or 'm'. ie) Returns just the '1' and '30 from the '1hr 30m' sample listed above.
String hours;
String minutes;
// Match the 'xxhr' and 'xxm' where x is either one or two numeric digits
// ie) Return '1hr' and '30m'
//Pattern p = Pattern.compile('([0-9]+hr) ([0-9]+m)');
// Match the hours and minutes without the 'hr' and 'm'. ie) Return '1' and '30'
Pattern p = Pattern.compile('(\\d+)(?=)hr (\\d+)(?=)m');
Matcher pm = p.matcher('1hr 30m');
if( pm.matches() )
{
hours = pm.group(1);
minutes = pm.group(2);
}
System.Debug('*** Hours: ' + hours);
System.Debug('*** Minutes: ' + minutes);
Attribution to: user3028
Possible Suggestion/Solution #2
Prep work
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
Use braces to define the parts you're interested in.
(\d+)h (\d+)m
Turn it into a string by escaping any backslashes
'(\\d+)h (\\d+)m'
Write the code
Create a Pattern object using your string
Use that to create a Matcher object.
Test to see if you got any matches using the Matcher's matches() function.
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 to: RickMeasham
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/185