包含一个或另一个单词的正则表达式

我需要创建一个表达式匹配一个完整的数字后面跟着“秒”或“分钟”

我试过这个表达: ([0-9]+)\s+(\bseconds\b)|(\bminutes\b)

它只能工作几秒钟,但不能工作几分钟。

例如,“5秒”给出5秒; 而“5分钟”给出; ; 分钟

148643 次浏览

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

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

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

Online demo

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

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