const regex = /[^\\](?:(?:\\{2})*)\$(?:(?:[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)|(?:{[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)})))/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('[^\\\\](?:(?:\\\\{2})*)\\$(?:(?:[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)|(?:{[=|-]?([A-Z0-9_]*[A-Z_]+[A-Z0-9_]*)})))', 'g')
const str = `\${HAVE_ERROR}
\\\\\${PATH}
\\\\\$SHELL
\\\\\\\\\${PATH}
\${HTTP_PORT}
\$HTTP_PORT
\$PORT
\$1_PORT
\${1_PORT}
\$PORT_345
\${PORT_345}
\${AZK_AGENT_CONF_FILE}
\${HTTP_HOST_2345}
\${=HTTP_HOST_2345}
\${-HTTP_HOST_2345}
\$ENV.HTTP
# ^ should match
# v should not match
any_text
LIKE_A_ENV_NAME
\\\${PATH}
\\\$SHELL
\\ \\\${PATH}
\\ \\\$SHELL
\\\\\\\${PATH}
\\\\\\\$SHELL
\$1
\${1}
\$@
\$?
\${env}
\${env.io}
\${ENV
\${ENV_hahaha}
\${ENV.HTTP}
\$envs.HTTP_PORT
\${envs.HTTP_PORT}
\${-net.host}
\${-net.port.http}
\${=net.port.http}
<%azk.default_domain%>
<%=manifest.dir%>
#{-system.name}
#{=manifest.dir}
#{azk}
#{azk.io}
##hello
\$hello
%hello%
<hello>`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions