Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression containing one word or another

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

like image 558
user965748 Avatar asked Jun 18 '13 10:06

user965748


People also ask

How do you regex multiple words?

However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.

How do you match a word in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

What is a word boundary regex?

A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ( [0-9A-Za-z_] ).


2 Answers

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

like image 121
micantox Avatar answered Oct 18 '22 15:10

micantox


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

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

Online demo

like image 21
Mistalis Avatar answered Oct 18 '22 15:10

Mistalis