如何用"替换字符串中的“(双引号)"在 Java 中 [英] how to replace "(double quotes) in a string with " in java

查看:22
本文介绍了如何用"替换字符串中的“(双引号)"在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串变量 strVar,其值为 ' "value1" ' 并且我想用 ' " ' 替换值中的所有双引号.所以之后替换值看起来像 ' "value1" '

I have string variable strVar with value as ' "value1" ' and i want to replace all the double quotes in the value with ' " '. So after replacement value would look like ' "value1" '

如何在java中做到这一点?请帮助我.

How to do this in java? Kindly help me.

推荐答案

您正在寻找

str = str.replace(""", "\"")

演示

我会避免使用 replaceAll 因为它使用正则表达式语法来描述要替换的内容和如何替换,这意味着 必须在字符串中转义 "\" 而且在正则表达式 \ 中(需要写成 "\\" 字符串),这意味着我们需要使用

I would avoid using replaceAll since it uses regex syntax in description of what to replace and how to replace, which means that will have to be escaped in string "\" but also in regex \ (needs to be written as "\\" string) which means that we would need to use

str = str.replaceAll(""", "\\"");

或者可能是小清洁工:

str = str.replaceAll(""", Matcher.quoteReplacement("\""))

通过replace,我们自动添加了转义机制.

With replace we have escaping mechanism added automatically.

这篇关于如何用"替换字符串中的“(双引号)"在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆