开发者

Regex to match whole words that begin with $

I need a regex to match whole words that begin with $. What is the expression, and how ca开发者_StackOverflow社区n it be tested?

Example:

This $word and $this should be extracted.

In the above sentence, $word and $this would be found.


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


For the testing part of you question I can recommend you using http://myregexp.com/


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜