Home > Mobile >  Regex function to match a specific sequence of characters
Regex function to match a specific sequence of characters

Time:12-27

I'm looking for a regex that would be True only in case that:

  • it starts with ${ (1 time, $ can only be there one time)
  • after that any characters or nothing until } is found

This would match:

${
${test
test${test
${$fdsf$
${test}

This would not match:

$${
$${test
${test}test

Hopefully it's clear :)

Is that possible ?

CodePudding user response:

Does that work for you?

(?<!\$)\$\{[^}]*}?$

https://regex101.com/r/g0vhJo/2

CodePudding user response:

Also use

([^$\n]|^)\$\{[^}\n]*}?$

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [^$\n]                   any character except: '$', '\n'
                             (newline)
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    ^                        the beginning of the string
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \$                       '$'
--------------------------------------------------------------------------------
  \{                       '{'
--------------------------------------------------------------------------------
  [^}\n]*                  any character except: '}', '\n' (newline)
                           (0 or more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  }?                       '}' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
  • Related