正则表达式去除'['和']'之间的空格 [英] Regex to remove spaces between '[' and ']'

查看:359
本文介绍了正则表达式去除'['和']'之间的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我一直在打破我的头。
在javascript中我有一个字符串表达式,我需要删除'['和']之间的空格。



例如表达式可以是: -

 名称] + [姓氏] + calculateAge()

我想要成为: p>

 [firstname] + [lastname] + calculateAge()

我尝试过从以下 stackoverflow问题的方括号,但没有完全达到。如何在该问题中使正则表达式也适用于方括号?



任何人都可以帮助?



谢谢,
AJ

解决方案

如果方括号始终是平衡的,如果它们从不嵌套,那么你可以做到:

  result = subject.replace(/ \s +(?= [^ [\]] * \]) /G, ); 

当且仅当有] 字符在字符串中,没有插入 [] 字符。



说明:

  \s +#匹配空格字符
(?=#如果可以匹配以下这里:
[^ [\]] *#除[或]
\]之外的任何数量的字符#后跟a]
)#先行断言结束。


I have been breaking my head on this for sometime now. In javascript I have a string expression where I need to remove the spaces between '[' and ']'.

For example the expression can be :-

"[first name] + [ last name ] + calculateAge()"

I want it to become :-

"[firstname] + [lastname] + calculateAge()"

I tried something from the following stackoverflow question for square brackets but didn't quite get there. How do I make the regex in that question, work for square brackets too?

Can anyone help?

Thanks, AJ

解决方案

If brackets are always balanced correctly and if they are never nested, then you can do it:

result = subject.replace(/\s+(?=[^[\]]*\])/g, "");

This replaces whitespace characters if and only if there is a ] character ahead in the string with no intervening [ or ] characters.

Explanation:

\s+       # Match whitespace characters
(?=       # if it's possible to match the following here:
 [^[\]]*  # Any number of characters except [ or ]
 \]       # followed by a ].
)         # End of lookahead assertion.

这篇关于正则表达式去除'['和']'之间的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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