如何使用JavaScript正则表达式提取字符串中的最后一个单词? [英] How to extract the last word in a string with a JavaScript regex?

查看:29
本文介绍了如何使用JavaScript正则表达式提取字符串中的最后一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是 last 比赛.如果单词 test 下方没有 $ 符号或任何其他特殊字符:

I need is the last match. In the case below the word test without the $ signs or any other special character:

测试字符串:

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

正则表达式:

\b(\w+)\b

推荐答案

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

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

\b(\w+)$

但是,您的测试字符串似乎具有美元符号定界符,因此,如果始终存在这些符号定界符,则可以使用它代替 \ b .

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

\$(\w+)\$$

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

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

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

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

\$(\w+)\$\s*$

最后,如果最后还有其他非单词内容,请改用 \ W * .

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

\b(\w+)\W*$

这篇关于如何使用JavaScript正则表达式提取字符串中的最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆