0

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?

1
  • You can try: (?=.)(hour|minute|second)? Commented Oct 29, 2020 at 6:58

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.