Some programming languages allow variable names to be specified as $VAR or ${VAR} where VAR is an alphanumeric sequence. This example shows how you can generate a regular expression to match any variable in either notation. You can find it as “Real world: $var and ${var} variable names” in the RegexMagic library.
$VARIABLE_NAME
${BETWEEN_BRACES}
$ANOTHER_VARIABLE
$VAR4
${VAR5}
$6
${7}
and detects it should match a literal $.
and also detects it as literal text. We’ll fix that later.
button above the sample. This tells RegexMagic that the second dollar sign in the sample starts a variable, just like the $ we already marked does.
. To make this happen, RegexMagic changes field
to be an alternation field. The field matching VARIABLE_NAME becomes field
, the first alternative under field
. The newly marked field for the opening brace is added as field
, the second alternative under field
.
consists of two consecutive fields (so far): the brace and BETWEEN_BRACES. To make this happen, RegexMagic changes
to be a sequence field. The field to match the brace becomes field
, and the newly marked BETWEEN_BRACES becomes field
.
.
or select field
in the “select field” drop-down list.
, change its pattern to “basic characters”, and tick “digits” and “lowercase letters”.
and
to repeat between 1 and 32 times or whatever lengths your variable names are allowed to have.
\$(?:[0-9A-Z_a-z]{1,32}|\{[0-9A-Z_a-z]{1,32}\})
Unused options: Case sensitive; Exact spacing; Dot doesn’t match line breaks; ^$ don’t match at line breaks; Numbered capture.
$VARIABLE_NAME ${BETWEEN_BRACES} $ANOTHER_VARIABLE $VAR4 ${VAR5} $6 ${7}
Essentially what we’ve done here is to separately mark all the different pieces of the text we’re trying to match so that we can use one RegexMagic Pattern for each of those pieces. Though it takes quite a number of steps, they’re all very straightforward. Once you get the hang of how RegexMagic combines patterns using alternation field and sequence fields you’ll be able to create your own regular expressions this way very quickly.