1

I'm trying to use RegEx to select all strings between two dollar signs.

text = text.replace(/\$.*\$/g, "meow");

I'm trying to turn all text between two dollar signs into "meow" (placeholder).

EDIT: Original question changed because the solution was too localized, but the accepted answer is useful information.

ramblinjan
  • 6,578
  • 3
  • 30
  • 38

2 Answers2

4

That's pretty close to what you want, but it will fail if you have multiple pairs of $text$ in your string. If you make your .* repeater lazy, it will fix that. E.g.,

text = text.replace(/\$.*?\$/g, "meow");
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • 2
    +1 didn't know about this. I would have used `[^\$]*` –  May 11 '12 at 18:08
  • Thanks! This essentially prevents mismatch from $'s as delimiters, right? – ramblinjan May 11 '12 at 18:10
  • This does solve one problem I might have in the future, but it still isn't working. I think it's something to do with the original text processing in the file. – ramblinjan May 11 '12 at 18:11
  • @jandjorgensen can you please give as a not working example? (In order we get to see what should be the result) –  May 11 '12 at 18:13
  • Hmm... I think we would have to see what the raw input looks like. Also it's possible you have some new lines messing with you. Can you provide a sample of the text as it is immediately prior to running the regular expression? – jmar777 May 11 '12 at 18:14
  • 2
    very interesting, i don't know this form. But I need to warn Bennika about the [ ] construct: you can use [^$] without the \ because every character inside a [ list ] is a literal character (except for the first ^ and the ] – Tiago Peczenyj May 11 '12 at 18:14
  • I found the problem in the other code. There's a input sanitizing function that I needed to add to to enable using it as a tag. Trying to decide what I should do as far as accepting an answer. – ramblinjan May 11 '12 at 18:17
  • Actually, here it is: // attacklab: Replace $ with ~D // RegExp interprets $ as a special character // when it's in a replacement string text = text.replace(/\$/g, "~D"); I'm going to change the question a bit and accept this as the answer because I think it's a really useful one. – ramblinjan May 11 '12 at 18:21
  • I was going to flag to close since my situation was too unique to be meaningful to future users, but I thought your solution was something someone searching might be interested in. – ramblinjan May 11 '12 at 21:59
3

I see one problem: if you have more than one "template" like

aasdasdsadsdsa $a$ dasdasdsd $b$ asdasdasdsa

your regular expression will consider '$a$ dasdasdsd $b$' as a text between two dolar signals. you can use a less specific regular expression like

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

to consider two strings in this example

Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35