aspose file tools*
The moose likes Beginning Java and the fly likes How to parse the hours and mins string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to parse the hours and mins string?" Watch "How to parse the hours and mins string?" New topic
Author

How to parse the hours and mins string?

divs saran
Greenhorn

Joined: Jan 09, 2008
Posts: 4
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.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874


divs,
first work out the format of the input String and use String's split() , subString() functions to get the numbers in them..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39805
    
  28
Look for classes like SimpleDateFormat.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39805
    
  28
You can probably set up a group like hours|h|hr|hour|hrs to capture "hours" and similarly for minutes.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

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>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to parse the hours and mins string?