You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串中$变量匹配需求:排除转义$,匹配偶数个\后的变量

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 \$var where 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:39