繁体   English   中英

如何使用正则表达式指定字符串分隔符?

[英]How to specify string delimiter using regex?

我有一个字符串'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(/(?<.{?*?)\/|(.<=}?*?)\//))

我不确定正则表达式方法,但您可以使用 function 像这样:

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);

从上面的评论...

...具有积极前瞻性的方法... /\/(?=(?:[^}]+\{)|(?:[^}{]+$)|$)/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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM