azimov azimov - 1 year ago 62
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
is a digit. No problem here,
works perfectly. The aim however is to identify separately each sequence
. The
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
. However for the first sequence
the only way I was able to make it work is
, which matches
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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download