vcima
vcima

Reputation: 453

Java Regex, Time pattern

I´m trying to obtain a regular expression that cover this combinations:

1h 
2m 
3s 
1h 2m 
1h 2m 3s 
2m 3s

So far, I have the next one: (\d+h\s?)?(\d+m\s?)?(\d+s\s?), but It doesn´t work fine.

Could anyone give me an idea?

Upvotes: 0

Views: 257

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

Try this regex:

(?:\d+h)(?: \d+m(?: \d+s)?)?|\d+m(?: \d+s)?|\d+s

Explanation:

(?:\d+h)(?: \d+m(?: \d+s)?)?     match 1h or 1h 2m or 1h 2m 3s
\d+m(?: \d+s)?                   match 2m or 2m 3s
\d+s                             match 3s

Follow the link below for Java code demonstrating this regex against your sample inputs.

Rextester

Upvotes: 1

Tezra
Tezra

Reputation: 8833

By grouping the interesting matches with |, You can match the valid portion of the string, with h, m, and s each captured in their own group so you can check if a particular line has a particular value. This is a great way to do optional matching with the completeness of full matching.

(?:\ ?(?:(\d+h)|(\d+m)|(\d+s)))+

(regex101)

Upvotes: 0

Sahil Gulati
Sahil Gulati

Reputation: 15141

Hope this will be helpful. Here we are using three combinations to prevent matching wrong patterns like 1h 3s, as it is not mentioned in desired OP's question.

Regex demo

Optionally if you want to restrict digits to only two digits you can change this \d+ to \d{2}

Regex: ^\d+[hms]$|^\d+[h]\s\d+[m](?:\s\d+[s])?$|^\d+m\s\d+s$

1. ^ start of string.

2. $ end of string.

3. \s is for single space

4. ^\d+[hms]$ one or more digit then either h , m and s

5. ^\d+[h]\s\d+[m](?:\s\d+[s])?$ this will match digits then h, then digits then m and at-last digits then s which is optional.

6. ^\d+m\s\d+s this will match digits then m and then digits then s

Upvotes: 0

Related Questions