如何使用正则表达式查找句子中的最后一个单词?
答案 0 :(得分:11)
如果您需要查找字符串中的最后一个单词,请执行以下操作:
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];
?>
答案 1 :(得分:3)
通常,您无法使用正则表达式正确解析英文文本。
你能做的最好的事情就是寻找一些通常会终止句子的标点符号,但遗憾的是这不是保证。例如,文本先生。 Bloggs就在这里。你想和他谈谈吗?包含两个具有不同含义的时期。正则表达式无法区分句点的两种用法。
我建议你看一下自然语言解析库。例如,Stanford Parser可以毫无困难地正确地将上述文本解析为两个句子:
Mr./NNP Bloggs/NNP is/VBZ here/RB ./. Do/VBP you/PRP want/VB to/TO talk/VB to/TO him/PRP ?/.
还有许多其他免费提供的NLP库也可以使用,我并不特别赞同这一个产品 - 它只是一个例子来证明可以将文本解析为具有相当高可靠性的句子。请注意,即使是自然语言解析库仍然偶尔会出错 - 正确解析人类语言很难。