Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to detect numbers written as words

Tags:

regex

php

I need PHP code to detect whether a string contains 4 or more consecutive written numbers (0 to 9), like :

"one four six nine five"

or

"zero eight nine nine seven three six six"
like image 838
Sherif Omar Avatar asked Aug 31 '10 10:08

Sherif Omar


People also ask

How do I find a word in a regular expression?

The regular expression \b[A]\w+ can be used to find all words in the text which start with A. The \b means to begin searching for matches at the beginning of words, the [A] means that these matches start with the letter A, and the \w+ means to match one or more word characters.

How do you write numbers in regular expressions?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

Can regex be used for numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


3 Answers

You can do it like this:

\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine)(?: +|$)){4}

(Rubular)

like image 58
Mark Byers Avatar answered Nov 16 '22 04:11

Mark Byers


Another option is:

\b(?:(?:one|two|three|four|five|six|seven|eight|nine|zero)\b\s*?){4}

That's pretty much the same as the rest. The only interesting bit is the \s*? part - that will lazily match the spaces between the words, so you don't end up with extra spaces after the sequence of 4 words. The \b before it assures there's at least a single space (or other separator after the last word, so !a b c d! will match)

like image 37
Kobi Avatar answered Nov 16 '22 03:11

Kobi


/(?:(?:^|\s)(?:one|two|three|four|five|six|seven|eight|nine|ten)(?=\s|$)){4,}/

PHP code:

if (preg_match(...put regex here..., $stringToTestAgainst)) {
    // ...
}

Note: More words (e.g. 'twelve') can easily be added to the regex.

like image 34
James Avatar answered Nov 16 '22 02:11

James