用字符串中的 `\r` 替换 `\\r` [英] replace `\\r` with `\r` in string

查看:58
本文介绍了用字符串中的 `\r` 替换 `\\r`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将所有出现的 \\r 转换为字符串中的 \r.

I need to convert all the occurrences of \\r to \r in string.

我的尝试如下:

    String test = "\\r New Value";
    System.out.println(test);
    test = test.replaceAll("\\r",  "\r");
    System.out.println("output: " + test);

输出:

\r New Value
output: \r New Value

推荐答案

使用 replaceAll 你将不得不使用 .replaceAll("\\\\r", "\r"); 因为

With replaceAll you would have to use .replaceAll("\\\\r", "\r"); because

  • 要在正则表达式中表示 \ 您需要对其进行转义,因此您需要使用 pass \\ 到正则表达式引擎
  • 但是要为单个 \ 创建字符串文字,您需要将其写为 "\\".
  • to represent \ in regex you need to escape it so you need to use pass \\ to regex engine
  • but and to create string literal for single \ you need to write it as "\\".

更清晰的方法是使用 replace("\\r", "\r"); 它将自动转义所有正则表达式元字符.

Clearer way would be using replace("\\r", "\r"); which will automatically escape all regex metacharacters.

这篇关于用字符串中的 `\r` 替换 `\\r`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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