我想我可以很容易地使用多个正则表达式来做这个,但我想替换字符串中的所有空格,但不是当这些空格在括号之间时.
例如:
Here is a string (that I want to) replace spaces in.
Run Code Online (Sandbox Code Playgroud)
在正则表达式后我想要字符串
Hereisastring(that I want to)replacespacesin.
Run Code Online (Sandbox Code Playgroud)
使用前瞻或外观操作符有一种简单的方法吗?
我对他们的工作方式有点困惑,并不确定他们会在这种情况下工作.
试试这个:
replace(/\s+(?=[^()]*(\(|$))/g, '')
Run Code Online (Sandbox Code Playgroud)
快速解释:
\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
Run Code Online (Sandbox Code Playgroud)
用简单的英语:它可以匹配一个或多个白色空格字符,如果(可以在前面看到一个或一个输入结尾,而不会遇到其间的任何括号.
在线Ideone演示:http://ideone.com/jaljw
如果: