Hoàng Tùng
Hoàng Tùng

Reputation: 120

Regular Expression: Prevent from matching empty string

I have this regex string

(hour)?|(minute)?|(second)?

which will match hourminutesecond or hourminute or hoursecond...

However, the regex also match an empty string ""

How can I exclude the empty string from the list of matches?

Upvotes: 0

Views: 124

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

If you don't need the separated capture groups for further processing, you could match at least one of the alternatives making none of them optional using a non capture group (?:

(?:hour|minute|second)

Regex demo

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520958

One quick fix here would be to add a positive lookahead which asserts that at least one character be present:

(?=.)(?:hour)?(?:minute)?(?:second)?

Note that the | in your current pattern are not doing what you think they are. The ? you place after each time term already make each term optional.

Demo

Upvotes: 1

Related Questions