简体   繁体   English

Java字符串附加双引号

[英]Java String appending a double quote

I want to replace all brackets in a String with the double quote character. 我想用双引号将字符串中的所有方括号替换。

I thought this would work: 我认为这可以工作:

"[foo".replaceAll(Pattern.quote("["), Pattern.quote("""));

but it does not. 但事实并非如此。 Can anyone help me understand what I need to do? 谁能帮助我了解我需要做什么?

您需要转义报价

"[foo".replaceAll(Pattern.quote("["), "\""); 

replaceAll takes strings replaceAll需要字符串

"[foo".replaceAll("\\[", "\""));

Might I also add this as a good place to test your regex strings 可能我也将此添加为测试您的正则表达式字符串的好地方

"[foo".replaceAll("\\[", "\"")

来转义字符串中的特殊字符,例如“ \\,您要在\\前面加上一个前缀,这样\\就会变成”,\\\\变成\\,等等。

"[foo".replaceAll(Pattern.quote("["), "\"") ;

第二个参数-替换-是一个通用字符串(不需要引号)。

The following works: 以下作品:

"[foo".replaceAll("\\[", "\\\\"") “ [foo” .replaceAll(“ \\ [”,“ \\\\”“)

Notes: 笔记:

  1. replaceAll interprets its first argument as a regular expression. replaceAll将其第一个参数解释为正则表达式。
  2. you need to escape (within the regex context) the opening bracket or it will be malformed. 您需要(在正则表达式中)转义左方括号,否则它将格式错误。

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

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