I need a regex to match whole words that begin with $. What is the expression, and how can it be tested?
Example:
This $word and $this should be extracted.
In the above sentence, $word
and $this
would be found.
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
A word boundary \b is a test, just like ^ and $ . When the regexp engine (program module that implements searching for regexps) comes across \b , it checks that the position in the string is a word boundary.
If you want to match only whole words, you need the word character selector
\B\$\w+
This will match a $
followed by one or more letters, numbers or underscore. Try it out on Rubular
\$(\w+)
Explanation :
\$
: escape the special $
character()
: capture matches in here (in most engines at least)\w
: match a - z
, A - Z
and 0 - 9
(and_
)+
: match it any number of times
I think you want something like this:
/(^\$|(?<=\s)\$\w+)/
The first parentheses just captures your result.
^\$ matches the beginning of your entire string followed by a dollar sign;
| gives you a choice OR;
(?<=\s)\$ is a positive look behind that checks if there's a dollar sign \$ with a space \s behind it.
Finally, (to recap) if we have a string that begins with a $ or a $ is preceded by a space, then the regex checks to see if one or more word characters follow - \w+.
This would match:
$test one two three
and
one two three $test one two three
but not
one two three$test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With