Javascript - 除非在括号内,否则除以空格 [英] Javascript - divide by spaces unless within brackets

查看:35
本文介绍了Javascript - 除非在括号内,否则除以空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用空格分隔字符串,但前提是空格不在方括号内.例如:

I want to divide a string by spaces, but only if the spaces are not within square brackets. For example:

多好的[晴天]"

分割后应该是这样的:

[什么,a,[晴朗],白天]

[What, a, [nice sunny], day]

我试图自己找到解决方案,但恐怕我对 javascript 中的 RegExp 不够熟悉.

I tried to find the solution on my own, but I'm afraid I'm not enough familiar with RegExp in javascript.

推荐答案

当必须包含空格时,需要以下正则表达式:

When the space has to be included, the following RegEx is needed:

"What a [nice sunny] day".match(/(^|\s)(\[[^\]]+\]|\S+)/g)
// Outputs: ["What"," a"," [nice sunny]"," day"]

在评论中,很明显必须删除空格:

In the comments, it became obvious that the spaces have to be removed:

"What a [nice sunny] day".match(/\[[^\]]+\]|\S+/g)
// Outputs: ["What","a","[nice sunny]","day"]

这篇关于Javascript - 除非在括号内,否则除以空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆