Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 查找句子中最后一个单词的正则表达式_Javascript_Regex - Fatal编程技术网

Javascript 查找句子中最后一个单词的正则表达式

Javascript 查找句子中最后一个单词的正则表达式,javascript,regex,Javascript,Regex,如何在带有正则表达式的句子中查找最后一个单词?如果需要在字符串中查找最后一个单词,请执行以下操作: 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 punctu

如何在带有正则表达式的句子中查找最后一个单词?

如果需要在字符串中查找最后一个单词,请执行以下操作:

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];

?> 

一般来说,您无法用正则表达式正确解析英文文本

你能做的最好的事情就是寻找一些通常会终止句子的标点符号,但不幸的是,这并不能保证。例如,Bloggs先生的文本就在这里。你想和他谈谈吗?包含两个具有不同含义的句点。正则表达式无法区分句点的两种用法

我建议您看看自然语言解析库。例如,将上述文本正确解析为两个句子完全没有问题:

Mr./NNP Bloggs/NNP is/VBZ here/RB ./. Do/VBP you/PRP want/VB to/TO talk/VB to/TO him/PRP ?/. 先生/NNP Bloggs/NNP is/VBZ here/RB./。 /VBP你/PRP想/VB跟他/说话/VB跟他/PRP吗?/。
还有很多其他免费提供的NLP库,你也可以使用,我并不特别支持这一产品——这只是一个例子,说明可以以相当高的可靠性将文本解析成句子。请注意,即使是自然语言解析库也会偶尔出错——正确解析人类语言是很困难的。

是的,我在每一个句号前都会对它进行解析,但你是对的,它会找到我不想要的先生。原始海报没有指定英语。有些语言不在单词之间加空格,所以我想知道程序是否能正确地挑出最后一个单词。有没有办法让我只用一个正则表达式,比如把它压缩成一个?因为我有一个我正在使用的函数,我只是不能让正则表达式工作它正在拾取句号和空格,其他什么都没有文本是用什么语言写的?英语?