views:

549

answers:

4

I need to find all matches of word which strictly begins with "$" and contains only digits. So I wrote

[$]\d+

which gave me 4 matches for

$10 $10 $20a a$20

so I thought of using word boundaries using \b:

[$]\d+\b

But it again matched

a$20 for me.

I tried

\b[$]\d+\b

but I failed.

I'm looking for saying, ACCEPT ONLY IF THE WORD STARTS WITH $ and is followed by DIGITS. How do I tell IT STARTS WITH $, because I think \b is making it assume word boundaries which means surrounded inside alphanumeric characters.

What is the solution?

+5  A: 

Not the best solution but this should work. (It does with your test case)

(?<=\s+|^)\$\d+\b
madgnome
This seems promising, can you tell how have you used this backreference?
Anirudh Goel
(?<=) is a Positive Backreference. It assert that the characters before the dollar match the regex between the parenthesis (here the beginning of the string or one or more space)
madgnome
Thanks. Can i have your gtalk id, i had some more queries.
Anirudh Goel
That's not a backreference, it's a positive lookbehind.
Alan Moore
+2  A: 

Have you tried

\B\$\d+\b

GoodEnough
This one works in my testing too; in your test string it finds the first two but ignores the second two.
Mike Powell
This worked well. But it failed if i test it for #$20, it matches it as well.
Anirudh Goel
Then I think you're going to have to use madgnome's regex.
Mike Powell
+1  A: 

Try with ^\$\d+

where ^ denoted the beginning of a string.

gcores
A: 

You were close, you just need to escape the $:

\B\$\d+\b

See the example matches here: http://regexhero.net/tester/?id=79d0ac3b-dd2c-4872-abb4-6a9780c91fc1

Andy Edinborough