How to extract the last word in a string with a Ja

2020-07-10 08:15发布

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

Test String:

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

Regex:

\b(\w+)\b

4条回答
淡お忘
2楼-- · 2020-07-10 08:29

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 \b matches an alphanumeric character next to a non-alphanumeric character. In your case this matches the '$' characters.

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+)\W+$
查看更多
走好不送
3楼-- · 2020-07-10 08:44

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.

\$(\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.

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

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

\b(\w+)\W*$
查看更多
Anthone
4楼-- · 2020-07-10 08:48

Avoid regex - use .split and .pop the result. Use .replace to remove the special characters:

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

DEMO

查看更多
Animai°情兽
5楼-- · 2020-07-10 08:51

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]

查看更多
登录 后发表回答