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
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
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:The
$
represents the end of the string, so...However, your test string seems to have dollar sign delimiters, so if those are always there, then you can use that instead of
\b
.If there could be trailing spaces, then add
\s*
before the end.And finally, if there could be other non-word stuff at the end, then use
\W*
instead.Avoid regex - use
.split
and.pop
the result. Use.replace
to remove the special characters:DEMO
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 usingpop()
on the result or by doing:result[result.length]