字符串替换regex只在[]之外使用令牌

时间:2021-05-16 16:50:01

I am trying to replace all the spaces in string with '+'. But it should ignore ignore the spaces inside the []. Do anyone know how to do this using regular expression.

我想用'+'替换字符串中的所有空格。但它应该忽略忽略[]内的空间。有人知道如何使用正则表达式来实现这一点吗?

Example:

例子:

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

should be replaced as

应该被取代

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

2 个解决方案

#1


2  

Replace ("global" flag enabled)

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

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

with

+

Explanation

解释

\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

This matches any space that is not inside a square bracket, under the assumption that there are no incorrectly opened/closed square brackets in the string and that square brackets are never nested.

这与任何不在方括号内的空间匹配,假设在字符串中没有错误地打开/关闭方括号,而方括号从不嵌套。

#2


1  

I suggest using a machine state instead of a regex. This way, you can stop replacing whitespaces when you're "inside" the []. If you go with a regex, you will likely need to use a lookahead, making it more complicate. There is a similar example here:
Replace whitespace outside quotes using regular expression

我建议使用机器状态而不是正则表达式。这样,当你在“内部”的时候,你就可以停止替换whitespaces。如果您使用regex,您可能需要使用lookahead,使其更加复杂。这里有一个类似的例子:使用正则表达式替换引号外的空格

#1


2  

Replace ("global" flag enabled)

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

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

with

+

Explanation

解释

\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

This matches any space that is not inside a square bracket, under the assumption that there are no incorrectly opened/closed square brackets in the string and that square brackets are never nested.

这与任何不在方括号内的空间匹配,假设在字符串中没有错误地打开/关闭方括号,而方括号从不嵌套。

#2


1  

I suggest using a machine state instead of a regex. This way, you can stop replacing whitespaces when you're "inside" the []. If you go with a regex, you will likely need to use a lookahead, making it more complicate. There is a similar example here:
Replace whitespace outside quotes using regular expression

我建议使用机器状态而不是正则表达式。这样,当你在“内部”的时候,你就可以停止替换whitespaces。如果您使用regex,您可能需要使用lookahead,使其更加复杂。这里有一个类似的例子:使用正则表达式替换引号外的空格