我想用'+'替换字符串中的所有空格。但它应该忽略忽略[]中的空格。有谁知道如何使用正则表达式来做到这一点。字符串替换正则表达式只在外面[]
实施例:
latitude[0 TO *] longitude[10 TO *]
应更换为
latitude[0 TO *]+longitude[10 TO *]
我想用'+'替换字符串中的所有空格。但它应该忽略忽略[]中的空格。有谁知道如何使用正则表达式来做到这一点。字符串替换正则表达式只在外面[]
实施例:
latitude[0 TO *] longitude[10 TO *]
应更换为
latitude[0 TO *]+longitude[10 TO *]
替换(启用 “全局” 标志)
\s(?=[^\]]*(?:\[|$))
与
+
说明
\s # white-space (use an actual space if you want)
(?= # but only when followed by (i.e. look-ahead)...
[^\]]* # ...anything but a "]"
(?: # non-apturing group ("either of")
\[ # "["
| # or
$ # the end of the string
) # end non-capturing group
) # end look-ahead
这个匹配不是方括号内,假设没有错误地打开/串中关闭方括号和方括号从未嵌套在任何空间。
我建议使用机器状态而不是正则表达式。这样,当你在[]内部时,可以停止替换空格。如果你使用正则表达式,你可能需要使用前瞻性,使其更加复杂。这里有一个类似的例子:
Replace whitespace outside quotes using regular expression