我有一個字串'w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0/c_overlay:{c_crop,w_300,h_300/main_image}/FFFFFF'。
我想將字串拆分為/,但是,我只想用作/不在{...}.
所以拆分字串后的結果將是:
['w_600,h_600', 'c_overlay{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0', 'c_overlay:{c_crop,w_300,h_300/main_image}', 'FFFFFF']
我嘗試使用,.split(/(?<!{.*?)\/|(?<=}.*?)\//)但如果有多個{...}.
console.log('w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0/c_overlay:{c_crop,w_300,h_300/main_image}/FFFFFF'.split(/(?<!{.*?)\/|(?<=}.*?)\//))
uj5u.com熱心網友回復:
我不確定正則運算式的方法,但你可以用這樣的函式來做到這一點:
TS游樂場
function splitOnTokenOutsideOpenClose (input, splitToken, openToken, closeToken) {
let nestingCount = 0;
let current = '';
const result = [];
for (const unit of input) {
if (unit === openToken) nestingCount = 1;
else if (unit === closeToken) nestingCount -= 1;
if (unit !== splitToken || nestingCount > 0) {
current = unit;
continue;
}
result.push(current);
current = '';
}
if (current.length > 0) result.push(current);
return result;
}
const input = `w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0/c_overlay:{c_crop,w_300,h_300/main_image}/FFFFFF`;
const result = splitOnTokenOutsideOpenClose(input, '/', '{', '}');
console.log(result);
uj5u.com熱心網友回復:
從上面的評論...
... 采用正向
/\/(?=(?:[^}] \{)|(?:[^}{] $)|$)/g預測的方法 ... ... 具有三個 OR 組合模式,以匹配/覆寫任何可能的分隔符出現。
// see ... [https://regex101.com/r/HYRvIM/1]
const regXSplit = /\/(?=(?:[^}] \{)|(?:[^}{] $)|$)/g;
console.log(
'w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0/c_overlay:{c_crop,w_300,h_300/main_image}/FFFFFF'
.split(regXSplit)
);
console.log(
'w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_image},g_center,y_-157,x_0/c_overlay:{c_crop,w_300,h_300/main_image}/FFFFFF/'
.split(regXSplit)
);
console.log(
'w_600,h_600/c_overlay:{c_fit,w_570,h_256/c_crop,w_600,h_600/main_im/age},g_center/,y_-157,x_0/c_overlay:{c_crop,w_/300,h_300/main_image}/FFF/FFF/'
.split(regXSplit)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389350.html
標籤:javascript 正则表达式 细绳 分裂
上一篇:正則運算式中前一行的回傳值
