正则表达式删除除括号之间的所有空格 [英] regex to remove all whitespaces except between brackets

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

问题描述

我一直在努力解决一个我希望用正则表达式解决的问题.

I've been wrestling with an issue I was hoping to solve with regex.

假设我有一个字符串,它可以包含任何字母数字,并且可能有一个子字符串被方括号包围.这些子字符串可以像这样出现在字符串中的任何位置.也可以有任意数量的括号括起来的子串.

Let's say I have a string that can contain any alphanumeric with the possibility of a substring within being surrounded by square brackets. These substrings could appear anywhere in the string like this. There can also be any number of bracket-ed substrings.

示例:

  • aaa[bb b]
  • aaa[bbb]ccc[d dd]
  • [aaa]bbb[c cc]

你可以看到一些括号中的子串中有空格,这很好.我现在的主要问题是当我遇到括号外的空格时:

You can see that there are whitespaces in some of the bracketed substrings, that's fine. My main issue right now is when I encounter spaces outside of the brackets like this:

  • a aa[bb b]

现在我想保留括号内的空格,但在其他地方删除它们.

Now I want to preserve the spaces inside the brackets but remove them everywhere else.

对于像这样的字符串,这会变得有点棘手:

This gets a little more tricky for strings like:

  • a aa[bb b]c cc[d dd]e ee[f ff]

这里我希望返回:

  • aaa[bb b]ccc[d dd]eee[f ff]

我现在花了一些时间阅读有关环视、否定断言等的不同 reg ex 页面,这让我头晕目眩.

I spent some time now reading through different reg ex pages regarding lookarounds, negative assertions, etc. and it's making my head spin.

注意:对于访问这里的任何人,我并不是在寻找任何涉及嵌套括号的解决方案.如果是这样的话,我可能会像下面提到的一些评论一样务实地去做.

NOTE: for anyone visiting this, I was not looking for any solution involving nested brackets. If that was the case I'd probably do it pragmatically like some of the comments mentioned below.

推荐答案

这个正则表达式应该可以解决问题:

This regex should do the trick:

[ ](?=[^\]]*?(?:\[|$))

只需替换与"匹配的空格即可.

Just replace the space that was matched with "".

基本上它所做的就是确保您要删除的空间前面有一个[",但如果它前面有一个]",则不会.

Basically all it's doing is making sure that the space you are going to remove has a "[" in front of it, but not if it has a "]" before it.

只要您没有嵌套的方括号,这应该可以工作,例如:

That should work as long as you don't have nested square brackets, e.g.:

a a[b [c c]b]

a a[b [c c]b]

因为在这种情况下,第一个b"后面的空格将被删除,它会变成:

Because in that case, the space after the first "b" will be removed and it will become:

aa[b[c c]b]

aa[b[c c]b]

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

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