Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match whole words that begin with $

Tags:

regex

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.

like image 313
node ninja Avatar asked May 04 '11 00:05

node ninja


People also ask

How do you search for a RegEx pattern at the beginning of a string?

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.

How do you find the whole word in a regular expression?

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.

What does \b mean in RegEx?

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.


3 Answers

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

like image 138
edgerunner Avatar answered Oct 13 '22 10:10

edgerunner


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

like image 18
Paystey Avatar answered Oct 13 '22 10:10

Paystey


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
like image 5
user1383418 Avatar answered Oct 13 '22 10:10

user1383418