前置字符集 [英] Prepend set of characters

查看:103
本文介绍了前置字符集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在给定字符串中对一组中出现的所有字符(比如'\ )添加一个反弹。

I need to prepend a backlash to all occurrences of characters from a set, say '"\, in a given string.

例如,给定字符串

He said "I don't know."

应替换为

He said \"I don\'t know.\"

我怎么用Java做这个?

How do I do this in Java?

推荐答案

试试这个正则表达式:

["'\\]

In为了在Java字符串文字中使用它,双引号和两个反斜杠都需要转义。

In order to use this in a Java string literal, the double quote and both backslashes need to be escaped.

替换字符串应为:

\\$0

这里 $ 0 是对比赛的引用。反斜杠需要转义,否则$变为文字。同样,反斜杠需要在Java字符串文字中进行转义。结果代码如下所示:

Here $0 is a reference to the match. The backslash needs to be escaped otherwise the $ becomes literal. Again the backslashes need to be escaped in a Java string literal. The resulting code looks like this:

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

在线查看: ideone

这篇关于前置字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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