简体   繁体   English

用正则表达式替换“ [”和“]”

[英]Regular Expression to replace “[” and “]”

I want a regular experssion for java to replace the "[" and the "]" . 我想要Java的常规扩展替换“ [”和“]”。 the compiler give error because [ is the syntax of regex. 编译器给出错误,因为[是regex的语法。 what should i do? 我该怎么办?

You just need to escape the special characters - \\[ and \\] . 您只需要转义特殊字符- \\[\\] This applies to all special characters too. 这也适用于所有特殊字符。

backslashes! 反斜杠! for any character that has a special meaning, you preface it with a backslash to match the literal character. 对于具有特殊含义的任何字符,请在其前面加上反斜杠以匹配文字字符。

Pattern = Pattern.compile("\\[\\]"); 

(pay attention that because it's java, you need two backslashes to equate to one backslash char). (请注意,因为它是Java,所以需要两个反斜杠才能等于一个反斜杠char)。

You could do: 您可以这样做:

String s = ...
s = s.replaceAll("\\[|]", "");

or: 要么:

s = s.replaceAll("[[\\]]", "");

or a non-regex replacement (so no escaping needed): 或非正则表达式替换(因此无需转义):

s = s.replace("[", "").replace("]", "");

An explanation of the regexes (the first 2 examples): 正则表达式的解释(前两个示例):

1: \\\\[|] 1: \\\\[|]

\\[    # match `[`
|      # OR
]      # match ']'

2: [[\\\\]] 2: [[\\\\]]

[      # start character class
  [    # match '[', or
  \\]  # match ']'
]      # end character class

Normally you can escape special characters with backslashes 通常您可以使用反斜杠转义特殊字符

\\[ \\ [

or 要么

\\] \\]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM