user15609698
user15609698

Reputation: 11

Regex match specific word with dollar sign?

I have sentences like:

$COIN has a new price target increase to $400

I only want to match $COIN with regex, I am wondering how to do this?

If I do something like .*\\$.* it also matches $400. I would just like to match the $SOMEWORDNOSPACE only. Is that possible?

Thanks

Upvotes: 0

Views: 658

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

(?<!\S)\$[A-Z]+(?!\S)

See proof

EXPLANATION

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    \S                       non-whitespace (all but \n, \r, \t, \f,
                             and " ")
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \$                       '$'
--------------------------------------------------------------------------------
  [A-Z]+                   any character of: 'A' to 'Z' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    \S                       non-whitespace (all but \n, \r, \t, \f,
                             and " ")
--------------------------------------------------------------------------------
  )                        end of look-ahead

Upvotes: 0

asdf101
asdf101

Reputation: 669

If everything after $ until the end of the word is a capital letter: \$[A-Z]+

This will match the $ (\$), and then match between 1 and infinity capital letters [A-Z]+. The match stops when a character doesn't fit in the A-Z range, so \b is unnecessary. If the match can't start in the middle of the sentence you could start with \B so it starts matching on a switch of a word character to the dollar sign, in that case the regex would be \B\$[A-Z]+

Upvotes: 1

Related Questions