简体   繁体   English

正则表达式,用于检测写为单词的数字

[英]regular expression to detect numbers written as words

I need PHP code to detect whether a string contains 4 or more consecutive written numbers (0 to 9), like : 我需要PHP代码来检测字符串是否包含4个或更多连续写入的数字(0到9),如:

"one four six nine five"

or 要么

"zero eight nine nine seven three six six"

You can do it like this: 你可以这样做:

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

(Rubular) (Rubular)

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*? 唯一有趣的是\\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. part - 将懒惰地匹配单词之间的空格,因此在4个单词的序列之后你不会得到额外的空格。 The \\b before it assures there's at least a single space (or other separator after the last word, so !abcd! will match) \\b之前它确保至少有一个空格(或最后一个单词之后的其他分隔符,所以!abcd!将匹配)

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

PHP code: PHP代码:

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

Note: More words (eg 'twelve') can easily be added to the regex. 注意:可以很容易地将更多单词(例如'12')添加到正则表达式中。

if (preg_match("/(?:\b(?:(one)|(two)|(three)|(four)|(five)|(six)|(seven)|(eight)|(nine))\b\s*?){4,}/", $variable_to_test_against, $matches)) {
  echo "Match was found <br />";
  echo $matches[0];
}

EDIT: 编辑:

Added space(s) in the regular expression - thanks to Kobi. 在正则表达式中添加了空格 - 感谢Kobi。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM