字符串中$变量匹配需求:排除转义$,匹配偶数个\后的变量
Solution for Matching $ Variables with Proper Escape Handling
Got it, let's break down how to write a regex that correctly matches $-prefixed variables while ignoring escaped \$ sequences—except when the backslash itself is escaped (i.e., \\$ should still match the variable).
The Regex Pattern
(?<!\\)(?:\\\\)*\$(\w+)
How It Works
Let's dissect each part to understand why this handles all edge cases:
(?<!\\): Negative lookbehind assertion – Ensures there isn't a single unpaired backslash immediately before the$. This rules out cases like\$varwhere the$is explicitly escaped.(?:\\\\)*: Non-capturing group – Matches 0 or more pairs of backslashes (\\\\). Each pair represents an escaped backslash in the original string, so these don't count as escape characters for the following$.\$: Matches the literal dollar sign we're targeting.(\w+): Capturing group – Grabs the variable name (assuming variables use alphanumeric characters and underscores; tweak this part if your variables allow other characters).
Example Usage
Here's how you'd implement this in common programming languages:
Python
import re sample_text = r""" - Plain variable: $username - Escaped $ (should NOT match): \$ignored - Escaped backslash + variable (should match): \\$email - Double-escaped backslash + variable (should match): \\\\$phone """ pattern = r"(?<!\\)(?:\\\\)*\$(\w+)" matched_vars = re.findall(pattern, sample_text) print(matched_vars) # Output: ['username', 'email', 'phone']
JavaScript
const sampleText = ` - Plain variable: $username - Escaped $ (should NOT match): \\$ignored - Escaped backslash + variable (should match): \\\\$email - Double-escaped backslash + variable (should match): \\\\\\\\$phone `; const pattern = /(?<!\\)(?:\\\\)*\$(\w+)/g; const matchedVars = [...sampleText.matchAll(pattern)].map(match => match[1]); console.log(matchedVars); // Output: ['username', 'email', 'phone']
Customizing for Variable Names
If your variables allow characters beyond \w (like dots, hyphens, or colons), replace \w+ with a character set that fits your needs:
- To allow hyphens and underscores:
([a-zA-Z0-9_-]+) - To allow any non-whitespace, non-backslash character:
([^\s\\]+)
内容的提问来源于stack exchange,提问作者unknown6656
相关产品推荐
相关产品推荐

