2011-08-31 59 views
2

我想用'+'替换字符串中的所有空格。但它应该忽略忽略[]中的空格。有谁知道如何使用正则表达式来做到这一点。字符串替换正则表达式只在外面[]

实施例:

latitude[0 TO *] longitude[10 TO *] 

应更换为

latitude[0 TO *]+longitude[10 TO *] 

回答

2

替换(启用 “全局” 标志)

\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 

这个匹配不是方括号内,假设没有错误地打开/串中关闭方括号和方括号从未嵌套在任何空间。