如何使用 JavaScript 正则表达式提取字符串中的最后一个单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30126201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:45:03  来源:igfitidea点击:

How to extract the last word in a string with a JavaScript regex?

javascriptregex

提问by ps0604

I need is the lastmatch. In the case below the word testwithout the $signs or any other special character:

我需要的是最后一场比赛。在下面test没有$符号或任何其他特殊字符的单词的情况下:

Test String:

测试字符串:

$this$ $is$ $a$ $test$ 

Regex:

正则表达式:

\b(\w+)\b

回答by six fingered man

The $represents the end of the string, so...

$代表字符串的结尾,所以...

\b(\w+)$

However, your test string seems to have dollar sign delimiters, so if those are always there, then you can use that instead of \b.

但是,您的测试字符串似乎有美元符号分隔符,因此如果它们始终存在,那么您可以使用它而不是\b.

$(\w+)$$

var s = "$this$ $is$ $a$ $test$";

document.body.textContent = /$(\w+)$$/.exec(s)[1];

If there could be trailing spaces, then add \s*before the end.

如果可能有尾随空格,则\s*在末尾添加。

$(\w+)$\s*$

And finally, if there could be other non-word stuff at the end, then use \W*instead.

最后,如果最后还有其他非单词的东西,那就用吧\W*

\b(\w+)\W*$

回答by Maarten Peels

var input = "$this$ $is$ $a$ $test$";

var input = "$this$ $is$ $a$ $test$";

If you use var result = input.match("\b(\w+)\b")an array of all the matches will be returned next you can get it by using pop()on the result or by doing: result[result.length]

如果您使用var result = input.match("\b(\w+)\b")所有匹配项的数组,接下来将返回您可以通过pop()在结果上使用或执行以下操作来获取它:result[result.length]

回答by Jonathan Mee

Your regex will find a word, and since regexes operate left to right it will find the first word.

您的正则表达式会找到一个单词,并且由于正则表达式从左到右运行,它将找到第一个单词。

A \w+matches as many consecutive alphanumeric character as it can, but it must match at least 1.
A \bmatches an alphanumeric character next to a non-alphanumeric character. In your case this matches the '$'characters.

A\w+匹配尽可能多的连续字母数字字符,但它必须至少匹配 1 个
。A\b匹配非字母数字字符旁边的字母数字字符。在您的情况下,这与'$'字符匹配。

What you need is to anchor your regex to the end of the input which is denoted in a regex by the $character.

您需要的是将您的正则表达式锚定到输入的末尾,该输入在正则表达式中由$字符表示。

To support an input that may have more than just a '$'character at the end of the line, spaces or a period for instance, you can use \W+which matches as many non-alphanumeric characters as it can:

为了支持'$'在行尾可能不仅仅是一个字符、空格或句点的输入,您可以使用\W+which 匹配尽可能多的非字母数字字符:

$(\w+)\W+$

回答by Andy

Avoid regex - use .splitand .popthe result. Use .replaceto remove the special characters:

避免正则表达式 - 使用.split.pop结果。使用.replace删除特殊字符:

var match = str.split(' ').pop().replace(/[^\w\s]/gi, '');

DEMO

演示