119

I need to create an expression matching a whole number followed by either "seconds" or "minutes"

I tried this expression: ([0-9]+)\s+(\bseconds\b)|(\bminutes\b)

It works fine for seconds, but not minutes.

E.g. "5 seconds" gives 5;seconds; while "5 minutes" gives ;;minutes

Richard Garside
  • 87,839
  • 11
  • 80
  • 93
user965748
  • 2,227
  • 4
  • 22
  • 30

3 Answers3

130

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

micantox
  • 5,446
  • 2
  • 23
  • 27
  • 24
    but thats an "extra match" that is not required. Either use `([0-9]+)\s+(?:(\bseconds\b)|(\bminutes\b))` or `([0-9]+)\s+(\bseconds\b|\bminutes\b)` – dognose Jun 18 '13 at 10:56
  • 4
    Yea that's true, no need for the brackets around \bseconds\b and \bminutes\b! – micantox Jun 18 '13 at 11:01
60

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Mistalis
  • 17,793
  • 13
  • 73
  • 97
4

If you care about the word boundaries and want to keep matches to a minimum use this:

([0-9]+)\s*\b(seconds|minutes)\b
Richard Garside
  • 87,839
  • 11
  • 80
  • 93