Search code examples
regexpcre

PCRE match a single character between curly braces


I write a PCRE trying to match dollar signs ($) only if they are between the curly braces.

My example text is like that: Lorem $100 ipsum dolor {value$banana} sit $500 amet.

The pattern (?<=\{)(.*?)(?=\}) gives me everything between the curly braces ({value$banana}), but I need to exactly match the dollar sign in between. I do not need a pattern matching multiple occurrences.

I've been trying to work on this but could not find the answer anywhere. Thanks in advance!


Solution

  • If you only want to match a single $ inside curly braces just once you may use

    '~\{[^{}$]*\K\$(?=[^{}]*})~'
    

    See the regex demo

    Details

    • \{ - a { char
    • [^{}$]* - 0 or more chars other than {, } and $
    • \K - match reset operator discarding all text matched so far from the match memory buffer
    • \$ - a $ char
    • (?=[^{}]*}) - a positive lookahead that requires the presence of any 0+ chars other than { and } and then a } immediately to the right of the current location.