简体   繁体   English

Java string.replace 不能作为 string.replaceAll 工作

[英]Java string.replace not working as string.replaceAll

I have an entry coming from database in the below format.我有一个来自数据库的条目,格式如下。 I first used replaceAll instead of replace function but SonarCloud show error and asks to change from replaceAll to replace.我首先使用 replaceAll 而不是 replace 函数,但 SonarCloud 显示错误并要求从 replaceAll 更改为 replace。 However, the replace dosen't replace all the backslash, infact it does not change anything in the text.但是,替换并不会替换所有的反斜杠,事实上它不会更改文本中的任何内容。

Entry from database in java code:用java代码从数据库中输入:

""{\"id\":\"5947223f-9c50-425f-950b-e126c94b3adf\",\"name\":\"shruti\"}

With replaceAll I wrote code as below which works fine:使用 replaceAll 我编写的代码如下,工作正常:

abcString.replaceAll("\\\\", "").replaceFirst("\"","");

To make SonarCloud happy, I try to change replaceAll with replace which in turn tell be to remove replaceFirst method otherwise it removes the both the double quotes from the database output.为了让 SonarCloud 开心,我尝试将 replaceAll 更改为 replace ,这反过来告诉是删除 replaceFirst 方法,否则它会从数据库输出中删除双引号。

Code with replace function:具有替换功能的代码:

abcString.replace("\\\\", "")

The second thing that I tried gives error:我尝试的第二件事给出了错误:

Unexpected character ('\' (code 92)): was expecting double-quote to start field name
!  at [Source: (String)"{\"id\":\"5947223f-9c50-425f-950b-e126c94b3adf\",\"name\":\"shruti\"}

Your real problem你真正的问题

JSON isn't regular at all, you can't just go messing with it like this. JSON 根本就不是常规的,你不能像这样把它弄乱。 You should use a real JSON parser, and whatever gave you this backslashified monstrosity is where the real bug lies.你应该使用一个真正的 JSON 解析器,无论给你这种反斜杠化的怪物是什么才是真正的错误所在。 The problem you're facing here can be 'fixed', but your code will remain a fragile mess until you fix this underlying problem!您在这里面临的问题可以“修复”,但在您解决这个潜在问题之前,您的代码将保持脆弱的混乱状态!

Your approach to SonarCloud您使用 SonarCloud 的方法

You shouldn't be using tools like this unless you understand what they do, and given that you ask this question with no idea as to why SonarCloud is even suggesting you replace replaceAll to replace, that sounds like this advice applies to you.您不应该使用这样的工具,除非您了解它们的作用,并且考虑到您问这个问题而不知道为什么 SonarCloud 甚至建议您替换 replaceAll 来替换,听起来这个建议适用于您。 Always read the reasoning behind a linting rule.始终阅读 linting 规则背后的推理。

The problem问题

.replaceAll replaces each occurrence, but is regular expression based. .replaceAll替换每次出现,但基于正则表达式。 .replace replaces each occurrence, and isn't - it just replaces the literal string you write. .replace替换每次出现,而不是 - 它只是替换您编写的文字字符串。 So, all you need to do is .replace("\\\\", "") .所以,你需要做的就是.replace("\\\\", "") The replaceAll requires 4 backslashes, because that becomes a string with 2 backslashes, which is regexp-ese for '1 backslash'. replaceAll 需要 4 个反斜杠,因为它变成了一个带有 2 个反斜杠的字符串,这是“1 个反斜杠”的 regexp-ese。

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

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