Reputation: 453
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
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.
Upvotes: 1
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
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.
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 space4.
^\d+[hms]$
one or more digit then eitherh
,m
ands
5.
^\d+[h]\s\d+[m](?:\s\d+[s])?$
this will matchdigits
thenh
, thendigits
thenm
and at-lastdigits
thens
which is optional.6.
^\d+m\s\d+s
this will matchdigits
thenm
and thendigits
thens
Upvotes: 0