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

查看:1273
本文介绍了如何用\"替换字符串中的“(双引号)”在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.

推荐答案

您正在寻找

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

DEMO

我会避免使用 replaceAll 因为它在描述什么时使用了正则表达式语法替换和如何替换,这意味着 \ 必须以字符串\\进行转义但也在正则表达式 \\ (需要写成\\\\ string)这意味着我们需要使用

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

replaceAll("\"", "\\\\\"");

或者可能是小清洁工:

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

替换我们自动添加了转义机制。

With replace we have escaping mechanism added automatically.

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

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