Riddle
Riddle

Reputation: 468

Matching "$" using regex in JavaScript

i am trying to write a regular expression for matching any words like which come in between "$" for example var myString = " there was a $dog$# and a $rat$ in a town"; i want to match dog and rat i have written the expresion for it

       var reg = /^$(.*)$/gmi 

but that does not because , the "$" being special character of end of line , how can i escape it , can i use "\" ?? can you pelase suggest the correct expression .

Upvotes: 0

Views: 90

Answers (5)

Máté
Máté

Reputation: 2345

As you said you should use '\' to escape the special characters. Also '^' is the start of the string you want to match for. You should use the following:

/\$(.*)\$/g

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44259

There is a problem with greediness, as you mentioned in a few comments. * will consume as much as possible, so if it is used like .* it will also consume further $ if it can find another one later one. There are two possibilities. The quickest and most common one is to simply make that quantifier ungreedy:

/\$(.*?)\$/g

Now it will consume as little as possible. The recommended way however is to make the repetition and the delimiter mutually exclusive and keep the repetition greedy:

/\$([^$]*)\$/g

This is generally more efficient, because no backtracking is needed. (Please don't hold me up on that, in any specific case the backtracking version might still be more efficient, but this is generally recommended practice)

Upvotes: 2

Amadan
Amadan

Reputation: 198324

/\$(.*)\$/

You use \ for escaping, as you thought. Also, given your requirements, ^ (start of string) is detrimental.

In case you have multiple appearances of such strings, you have to be careful of greediness (the default), so you either disallow the terminator from the contents:

/\$([^$]*)\$/g

or you make the repetition operator non-greedy:

/\$(.*?)\$/g

Upvotes: 1

complex857
complex857

Reputation: 20753

Yes, escaping is done with \ -s, if you want to catch individual $...$ marked words try this regexp:

/\$([^$]+)\$/gmi // inside character classes ( the []-s) you don't need to escape it, but if you do it does the same thing

Upvotes: 1

Richard
Richard

Reputation: 108975

can i use "\" ??

Yes.

Why didn't you try that yourself?

var reg = /^\$(.*)\$/gmi

will match:

  • Start of string
  • A $
  • Zero of more characters
  • A $

Upvotes: 0

Related Questions