Question

I want to get and replace Strings within a specific pattern: $here is a string$ should be replaced with $$$here is a string$$$. However there can also occurences of $$ or $$here is text$$ which should not be replaced.

I use this: \$.+?(\$) search-pattern and it avoids $$ these empty dollar signs pretty well, however it still finds these: $$text$$ which it shouldn't. (Well due to the nature of it, it actually finds $$text$, but that's not really better)

I need to find a way to forbid another $ to appear after the last $ (probably using regex negations), but how?

Thanks in advance.

Was it helpful?

Solution

If you have lookarounds available:

(?<!\$)\$[^$]+\$(?!\$)

EDIT: Including comments

(?<!\$)          # Negative lookbehind.  The character before this cannot
                 #  be a $ (it can be the beginning of the string since
                 #  this is a zero-width assertion
\$               # literal $
[^$]             # Character class meaning "anything but a $"
+                # Match one or more of this character class
\$               # literal $
(?!\$)           # Negative lookahead.  Similar to the lookbehind, but
                 # this cannot be *followed* by $

OTHER TIPS

You are selecting on any character after the dollar sign. instead, try to do any character BUT the dollar sign. You can also use curly brackets to limit the number of matches to 1.

\$[^$]+?\${1}

{n,m} matches the pattern between n and m times

{n} matches the pattern exactly n times

[^...] matches all characters that do not match the given character set

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top