Reputation: 32986
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.
Upvotes: 18
Views: 51276
Reputation: 14973
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
Upvotes: 23
Reputation: 664
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
Upvotes: 5
Reputation: 3242
\$(\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
Upvotes: 18
Reputation: 3859
Try this as your regex:
/ (\$\w+)/
\w+
means "one or more word characters". This matches anything beginning with $ followed by word characters, but only if it's preceded by a space.
You could test it with perl (the \ after the echo is just to break the long line):
> echo 'abc $def $ ghi $$jkl mnop' \
| perl -ne 'while (/ (\$\w+)/g) {print "$1\n";} '
$def
If you don't use the space in the regex, you'll match the $jkl
in $$jkl
- not sure if that is what you want:
> echo 'abc $def $ ghi $$jkl mnop' \
| perl -ne 'while (/(\$\w+)/g) {print "$1\n";} '
$def
$jkl
Upvotes: 0
Reputation: 80384
This should be self-explanatory:
\$\p{Alphabetic}[\p{Alphabetic}\p{Dash}\p{Quotation_Mark}]*(?<!\p{Dash})
Notice it doesn’t try to match digits or underscores are other silly things that words don’t have in them.
Upvotes: 0
Reputation: 764
For the testing part of you question I can recommend you using http://myregexp.com/
Upvotes: 1