user1700851
user1700851

Reputation: 3

Regular expression to find $ signs but not ones with {} around them

I'm trying to write a regular expression to escape $ signs that are not surrounded by {}.

This is what I have so far: \^\$|[^\{]\$\

$test 

expected: match actual: match

{$test1}

expected: no match actual: no match

{$test}  $test1

expected: match 2nd actual: matches space before 2nd $ sign

{ $test3 }

expected: no match actual: matches space before $ sign

So basically if a $ is enclosed by brackets, it should never match, but any other $ should match.

I'm using php and I'm assuming there is no nesting of brackets.There can be whitespace (n spaces or linebreaks or tabs, any kind of whitespace) between brackets and $ signs.

Upvotes: 0

Views: 100

Answers (2)

Narendra Yadala
Narendra Yadala

Reputation: 9664

This should work for you assuming no nested parentheses

$result = preg_replace('/\$(?![^{]*\})/m', '', $subject);

Explanation

"
\$         # Match the character “$” literally
(?!        # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   [^{]       # Match any character that is NOT a “{”
      *          # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   }          # Match the character “}” literally
)
"

Upvotes: 3

user1937198
user1937198

Reputation: 5348

How about: \^(?:{[^}]*}|[^{])*\$\ the substitute with $1\\$

Upvotes: 0

Related Questions