查找字符字符,除非被特定字符包围



我有一个字符串:"${styles.button} ${styles[color]} ${styles[size]} ${styles[_state]} ${iconOnly ? styles.iconOnly : ''}",我正在尝试使用正则表达式查找所有空格,除了属于插值字符串 (${...}的空格(。

我愿意承认正则表达式可能不是这项工作的正确工具,但我很好奇我错过了什么。

本质上,我要做的是用换行符替换空格。

您可以将字符串拆分为插值字符串和非插值字符串序列,然后仅修改奇数序列(生成的数组始终以非插值字符串开头,不用担心(。必须这样做,因为正则表达式在它们可以记住的状态中受到限制(有关该研究CS的更多信息(。解决方案是:

var string = "${styles.button} ${styles[color]} ${styles[size]} ${styles[_state]} ${iconOnly ? styles.iconOnly : ''}";
var result = string
// split in non-interpolation string and interpolation string sequences
.split(/(${[^}]*})/g)
// modify the sequences with odd indices ( non-interpolation)
.map((part, i) => (i % 2 ? part : part.replace(/ +/g, '')))
// concatenate the strings
.join('');
console.log(result);

但也要注意 ggorlen 对您的问题的评论:

看起来您正在尝试使用正则表达式来解析任意 JS 模板字符串。在一般情况下,这不是一件容易的事,正则表达式可能是这项工作的错误工具 - 这可能是一个 xy 问题。你能提供更多的上下文(为什么你需要首先解析JS模板字符串?(并展示一个尝试吗?谢谢。

假设您只有${...}模式,按照您的示例用空格分隔,您可以应用此正则表达式:

var str = "${styles.button} ${styles[color]} ${styles[size]} ${styles[_state]} ${iconOnly ? styles.iconOnly : ''}"
var re = /(}) +(${)/g;
var result = str.replace(re, "$1n$2");
console.log('result: ' + result);

结果:

result: ${styles.button}
${styles[color]}
${styles[size]}
${styles[_state]}
${iconOnly ? styles.iconOnly : ''}

我用一个简单的查找"\$"(不带引号(进行了测试,替换为"$"(不带引号(-在崇高的文本正则表达式搜索中,效果很好

最新更新