Python (re)

Unix Environment Variable Reference in PY

Match Unix shell environment variable references in both $VAR and ${VAR} forms.

Try it in the PY tester →

Pattern

regexPY
\$\{?([A-Z_][A-Z0-9_]*)\}?   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"\$\{?([A-Z_][A-Z0-9_]*)\}?")
input_text = "Path is $HOME/.config"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

\$ matches the literal dollar sign. \{? optionally matches an opening brace. ([A-Z_][A-Z0-9_]*) captures the variable name: must start with a letter or underscore, followed by letters, digits, or underscores. \}? optionally matches the closing brace.

Examples

Input

Path is $HOME/.config

Matches

  • $HOME

Input

export ${DATABASE_URL}

Matches

  • ${DATABASE_URL}

Input

no variables here

No match

Same pattern, other engines

← Back to Unix Environment Variable Reference overview (all engines)