java 如何用单斜杠替换特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3302715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:12:13  来源:igfitidea点击:

How to replace a special character with single slash

java

提问by swati

I have a question about strings in Java. Let's say, I have a string like so:

我有一个关于 Java 字符串的问题。比方说,我有一个像这样的字符串:

String str = "The . startup trace ?state is info?";

As the string contains the special character like "?"I need the string to be replaced with "\?"as per my requirement. How do I replace special characters with "\"? I tried the following way.

由于字符串包含特殊字符,就像"?"我需要"\?"根据我的要求替换字符串一样。如何用 替换特殊字符"\"?我尝试了以下方法。

str.replace("?","\?"); 

But it gives a compilation error. Then I tried the following:

但它给出了编译错误。然后我尝试了以下方法:

str.replace("?","\?");

When I do this it replaces the special characters with "\\". But when I print the string, it prints with single slash. I thought it is taking single slash only but when I debugged I found that the variable is taking "\\".

当我这样做时,它将特殊字符替换为 "\\". 但是当我打印字符串时,它用单斜杠打印。我以为它只使用单斜杠,但是当我调试时,我发现该变量正在使用"\\".

Can anyone suggest how to replace the special characters with single slash ("\")?

谁能建议如何用单斜杠 ( "\")替换特殊字符?

回答by polygenelubricants

On escape sequences

关于转义序列

A declaration like:

像这样的声明:

String s = "\";

defines a string containing a single backslash. That is, s.length() == 1.

定义一个包含单个反斜杠的字符串。也就是说,s.length() == 1

This is because \is a Java escape character for Stringand charliterals. Here are some other examples:

这是因为\Stringchar文字的 Java 转义字符。以下是一些其他示例:

  • "\n"is a Stringof length 1 containing the newline character
  • "\t"is a Stringof length 1 containing the tab character
  • "\""is a Stringof length 1 containing the double quote character
  • "\/"contains an invalid escape sequence, and therefore is not a valid Stringliteral
    • it causes compilation error
  • "\n"String包含换行符的长度为 1 的
  • "\t"String包含制表符的长度为 1 的
  • "\""String包含双引号字符的长度为 1 的
  • "\/"包含无效的转义序列,因此不是有效的String文字
    • 它导致编译错误

Naturally you can combine escape sequences with normal unescaped characters in a Stringliteral:

自然地,您可以在String文字中将转义序列与普通的未转义字符组合起来:

System.out.println("\"Hey\\nHow\tare you?");

The above prints (tab spacing may vary):

以上打印(标签间距可能会有所不同):

"Hey\
How are you?

References

参考

See also

也可以看看



Back to the problem

回到问题

Your problem definition is very vague, but the following snippet works as it should:

您的问题定义非常模糊,但以下代码段按其应有的方式工作:

System.out.println("How are you? Really??? Awesome!".replace("?", "\?"));

The above snippet replaces ?with \?, and thus prints:

上面的代码片段替换?\?, 从而打印:

How are you\? Really\?\?\? Awesome!

If instead you want to replace a charwith another char, then there's also an overload for that:

相反,如果您想char用 another替换 a char,那么还有一个重载:

System.out.println("How are you? Really??? Awesome!".replace('?', '\'));

The above snippet replaces ?with \, and thus prints:

上面的代码片段替换?\, 从而打印:

How are you\ Really\\ Awesome!

StringAPI links

String接口链接



On how regex complicates things

关于正则表达式如何使事情复杂化

If you're using replaceAllor any other regex-based methods, then things becomes somewhat more complicated. It can be greatly simplified if you understand some basic rules.

如果您正在使用replaceAll或任何其他基于正则表达式的方法,那么事情会变得有些复杂。如果您了解一些基本规则,则可以大大简化。

  • Regex patterns in Java is given as Stringvalues
  • Metacharacters (such as ?and .) have special meanings, and may need to be escaped by preceding with a backslash to be matched literally
  • The backslash is also a special character in replacement Stringvalues
  • Java 中的正则表达式模式以String值的形式给出
  • 元字符(如?and .)有特殊含义,可能需要在前面加上反斜杠进行转义,才能按字面意思匹配
  • 反斜杠也是替换String值中的特殊字符

The above factors can lead to the need for numerous backslashes in patterns and replacement strings in a Java source code.

上述因素可能导致在 Java 源代码中的模式和替换字符串中需要大量反斜杠。

It doesn't look like you need regex for this problem, but here's a simple example to show what it can do:

看起来你不需要正则表达式来解决这个问题,但这里有一个简单的例子来展示它可以做什么:

    System.out.println(
        "Who you gonna call? GHOSTBUSTERS!!!"
            .replaceAll("[?!]+", "<
Who you gonna call<?> GHOSTBUSTERS<!!!>
>") );

The above prints:

上面的打印:

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

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

The pattern [?!]+matches one-or-more (+) of any characters in the character class [...]definition (which contains a ?and !in this case). The replacement string <$0>essentially puts the entire match $0within angled brackets.

该模式[?!]+匹配+字符类[...]定义中的一个或多个 ( ) (在本例中包含 a?!)。替换字符串<$0>基本上将整个匹配项$0放在尖括号内。

Related questions

相关问题

Regular expressions references

正则表达式参考

回答by True Soft

In case you want to replace ?with \?, there are 2 possibilities: replaceand replaceAll(for regular expressions):

如果您想替换?\?,有两种可能性:replacereplaceAll(对于正则表达式):

        String str="\";
        str=str.replace(str,"\\");
        System.out.println("New String="+str);

The result is "The . startup trace \?state is info\?"

结果是 "The . startup trace \?state is info\?"

If you want to replace ?with \, just remove the ?character from the second argument.

如果要替换?\,只需?从第二个参数中删除该字符。

回答by user207421

But when I print the string, it prints with single slash.

但是当我打印字符串时,它用单斜杠打印。

Good. That's exactly what you want, isn't it?

好的。这正是你想要的,不是吗?

There are two simple rules:

有两个简单的规则:

  1. A backslash inside a String literal has to be specified as two to satisfy the compiler, i.e. "\". Otherwise it is taken as a special-character escape.

  2. A backslash in a regular expresion has to be specified as two to satisfy regex, otherwise it is taken as a regexescape. Because of (1) this means you have to write 2x2=4 of them:"\\\\" (and because of the forum software I actually had to write 8!).

  1. 字符串文字中的反斜杠必须指定为两个以满足编译器的要求,即“\”。否则,它被视为特殊字符转义。

  2. 正则表达式中的反斜杠必须指定为两个以满足正则表达式,否则将被视为正则表达式转义。因为 (1) 这意味着你必须写 2x2=4 个:"\\\\"(而且因为论坛软件,我实际上不得不写 8 个!)。

回答by JDGuide

##代码##

Out put:- New String=\

输出:- 新字符串=\

In java "\\"treat as "\". So, the above code replace a "\"single slash into "\\".

在 java 中"\\"视为"\". 因此,上面的代码将"\"单个斜杠替换为"\\".