# How to parse the hours and mins string?

divs saran

Greenhorn

Posts: 4

posted 6 years ago

Hi,

How to parse string with hours and mins to mins? sample input strings are- 10 hours 30 mins, 1 hour, 2 hours, 45mins, 1 min. I have to convert the time to mins.

Any help is appreciated.

How to parse string with hours and mins to mins? sample input strings are- 10 hours 30 mins, 1 hour, 2 hours, 45mins, 1 min. I have to convert the time to mins.

Any help is appreciated.

Campbell Ritchie

Sheriff

Posts: 48972

60

posted 6 years ago

That doesn't support using words like "hours" and "minutes".

I think regular expressions can help you out. You want the following:

1) a number, any number of spaces, the word "hours" - the number is the number of hours

2) a number, any number of spaces, the word "minutes" - the number is the number of minutes

3) a combination of the above two

One regular expression with two parts, each optional and each with a capturing group, could help you out quite easily - once you've set up the regex that is. Check out java.util.regex.Pattern and its full Javadoc page.

I think regular expressions can help you out. You want the following:

1) a number, any number of spaces, the word "hours" - the number is the number of hours

2) a number, any number of spaces, the word "minutes" - the number is the number of minutes

3) a combination of the above two

One regular expression with two parts, each optional and each with a capturing group, could help you out quite easily - once you've set up the regex that is. Check out java.util.regex.Pattern and its full Javadoc page.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

Campbell Ritchie

Sheriff

Posts: 48972

60

posted 6 years ago

And of course make it case insensitive.

<nitpicking>

hours|h|hr|hour|hrs is not optimal. You can optimize this by splitting of common parts (added parentheses and spaces to make it clearer):

That said, I would use your regex too. It may be suboptimal, but it's so much easier to understand.

</nitpicking>

<nitpicking>

hours|h|hr|hour|hrs is not optimal. You can optimize this by splitting of common parts (added parentheses and spaces to make it clearer):

That said, I would use your regex too. It may be suboptimal, but it's so much easier to understand.

</nitpicking>

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions