java正斜杠,Java Regex中的正斜杠

I can't figure out why the following code doesn't behave as expected

"Hello/You/There".replaceAll("/", "\\/");

Expected output: Hello\/You\/There

Actual output: Hello/You/There

Do I need to escape forward slashes? I didn't think so but I also tried the following against my will ... didn't work

"Hello/You/There".replaceAll("\\/", "\\/");

In the end I realized I don't need a regular expression and I can just use the following, which doesn't create a regular expression

"Hello/You/There".replace("/", "\\/");

However, I'd still like to understand why my first example doesn't work.

解决方案

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值