如何使用正则表达式查找句子中的最后一个单词?
如果你需要找到一个字符串的最后一个单词,可以这样做:
m/
(\w+) (?# Match a word, store its value into pattern memory)
[.!?]? (?# Some strings might hold a sentence. If so, this)
(?# component will match zero or one punctuation)
(?# characters)
\s* (?# Match trailing whitespace using the * because there)
(?# might not be any)
$ (?# Anchor the match to the end of the string)
/x;
执行完这条语句后,$1会保存字符串中的最后一个单词。你可能需要通过添加更多的标点符号来扩展字符类[.!?]。
在PHP中:
<?php
$str = 'MiloCold is Neat';
$str_Pattern = '/[^ ]*$/';
preg_match($str_Pattern, $str, $results);
// Prints "Neat", but you can just assign it to a variable.
print $results[0];
?>
还有很多其他免费可用的NLP库,你也可以使用它们,我并不特别支持某个产品 - 这只是一个示例,以证明可以相当可靠地将文本解析成句子。请注意,即使是自然语言解析库也会偶尔出错 - 正确解析人类语言很难。