替换空格,但不替换括号之间的空格

Replace spaces but not when between parentheses

本文关键字:替换 空格 之间      更新时间:2023-09-26

我想我可以用多个正则表达式相当容易地做到这一点,但我想替换字符串中的所有空格,但不是当这些空格在括号之间时。

例如:

Here is a string (that I want to) replace spaces in.

在正则表达式之后,我希望字符串是

Hereisastring(that I want to)replacespacesin.

是否有一种简单的方法可以使用向前看或向后看操作符来做到这一点?

我对它们是如何工作的有点困惑,不确定它们是否能在这种情况下工作。

试试这个:

replace(/'s+(?=[^()]*('(|$))/g, '')

快速解释:

's+          # one or more white-space chars
(?=          # start positive look ahead
  [^()]*     #   zero or more chars other than '(' and ')'
  (          #   start group 1
    '(       #     a '('
    |        #     OR
    $        #     the end of input
  )          #   end group 1
)            # end positive look ahead

简单地说:如果(或输入结束符可以在前面看到而没有遇到任何括号,则匹配一个或多个空白字符。

在线Ideone演示:http://ideone.com/jaljw

如果:

  • 有嵌套括号
  • 括号可以转义