How to extract hours and minutes from time format string using RegEx in Flutter

I’m working on a Flutter app where I need to parse time duration strings that come in a specific format. I have strings like 4h 15m that represent work hours logged in my application.

I want to use regular expressions to extract the hour and minute values from these formatted strings. The format is always the same - it has a number followed by ‘h’ for hours, then a space, then another number followed by ‘m’ for minutes.

What would be the best RegEx pattern to capture both the hour and minute values separately so I can use them in my Flutter calculations? I need to be able to handle different numbers like 2h 45m, 8h 0m, or 12h 30m.

The pattern r'(\d+)h (\d+)m' works perfectly. I built something similar last year for a project tracker. I wrapped the regex in a simple method that returns a Map with the extracted values - something like Map<String, int> parseTimeString(String input) using RegExp.allMatches() and converting the captured groups to integers directly. Saved me from scattering string-to-int conversion all over the codebase. Just heads up - this pattern assumes your input’s always well-formed, so you might need validation depending on how reliable your data source is.

skip regex - it’s overkill. use split() instead: var parts = timeStr.split(' '); var hours = int.parse(parts[0].replaceAll('h', '')); var mins = int.parse(parts[1].replaceAll('m', '')); way simpler and faster for basic formats like this.

Had this exact problem a few months ago building a timesheet tracker. This regex worked perfectly: /(\d+)h (\d+)m/ - you need the double backslashes in Dart strings for proper escaping. Use it like: RegExp r = RegExp(r'(\d+)h (\d+)m'); then r.firstMatch(yourString) to get the match. First capture group = hours, second = minutes. Don’t forget to check for null if your input doesn’t match the format. Been rock solid in production handling thousands of entries daily.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.