azimov azimov - 11 months ago 41
Java Question

Match first occurrence of a string

Example of string:

Alerts will be silent from 00:00 to 05:00
. The regex must match any sequence with following format
nn:nn
where
n
is a digit. No problem here,
[0-9]{2}:[0-9]{2}
works perfectly. The aim however is to identify separately each sequence
00:00
and
05:00
. The
00:00
and
05:00
represent hours, the reason I need to identify them separately is because string must be updated with relevant hours.

The following regex works to match
05:00
:
[0-9]{2}:[0-9]{2}$
. However for the first sequence
00:00
the only way I was able to make it work is
\s[0-9]{1,2}:[0-9]{2}\s
, which matches
00:00
but with whitespaces at both ends. Of course this is not desired result, the sequence must be matched without whitespaces.

Answer Source

It seems that your problem can be solved in a different way, but you only provided few details.

Addressing the main issue, mainly:

the sequence must be matched without whitespaces

note that \s[0-9]{1,2}:[0-9]{2}\s contains \s as part of the consuming pattern. To just check if the whitespaces are present or absent, you should use lookarounds, or zero-width assertions.

(?<=\s)[0-9]{1,2}:[0-9]{2}(?=\s)

Here, (?<=\s) requires the presence of a whitespace before the first 1 or 2 digits, but it does not consume this whitespace. (?=\s) positive lookahead requires the presence of a whitespace after the trailing 1 or 2 digits, and is not consumed either.

By "consumed" I mean the matched substring does not make part of the returned match value.