源串:234bad{123}abca34{12}abaca12
目標:大括號 外 的數字替換為 *,大括號 內 保持不變。
結果:***bad{123}abca**{12}abaca**
// 正則
\d(?![^{}]*})
// 解釋
\d # 匹配一個數字
(?![^{}]*}) # 負向前瞻:斷言後面沒有「非大括號字符後跟 }」,即不在 {} 內
const str = '234bad{123}abca34{12}abaca12';
const res = str.replace(/\d(?![^{}]*})/g, '*');
console.log(res); // ***bad{123}abca**{12}abaca**
String res = str.replaceAll("\\d(?![^{}]*})", "*");
import re
res = re.sub(r'\d(?![^{}]*})', '*', str)
若存在 {a{1}b},上述正則失效。需用 遞歸正則(PCRE/Go/Java 不支持)或 狀態機解析:
function replaceOutsideBraces(s) {
let depth = 0, out = '';
for (let ch of s) {
if (ch === '{') depth++;
else if (ch === '}') depth--;
out += (depth === 0 && /\d/.test(ch)) ? '*' : ch;
}
return out;
}
在線測試:regex101.com 貼入正則 \d(?![^{}]*}) 即時高亮匹配位置。