开发者

How to replace a special character with single slash

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

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 cha开发者_Go百科racters 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 ("\")?


On escape sequences

A declaration like:

String s = "\\";

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

This is because \ is a Java escape character for String and char literals. Here are some other examples:

  • "\n" is a String of length 1 containing the newline character
  • "\t" is a String of length 1 containing the tab character
  • "\"" is a String of length 1 containing the double quote character
  • "\/" contains an invalid escape sequence, and therefore is not a valid String literal
    • it causes compilation error

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

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

The above prints (tab spacing may vary):

"Hey\
How are you?

References

  • JLS 3.10.6 Escape Sequences for Character and String Literals

See also

  • Is the char literal '\"' the same as '"' ?(backslash-doublequote vs only-doublequote)

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 char with another char, then there's also an overload for that:

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

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

How are you\ Really\\\ Awesome!

String API links

  • replace(CharSequence target, CharSequence replacement)
    • Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
  • replace(char oldChar, char newChar)
    • Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

On how regex complicates things

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

  • Regex patterns in Java is given as String values
  • 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 String values

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

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("[?!]+", "<$0>")
    );

The above prints:

Who you gonna call<?> GHOSTBUSTERS<!!!>

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 $0 within angled brackets.

Related questions

  • Having trouble with Splitting text. - discusses common mistakes like split(".") and split("|")

Regular expressions references

  • regular-expressions.info
    • Character class and Repetition with Star and Plus
  • java.util.regex.Pattern and Matcher


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

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

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

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

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


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 regex escape. 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!).


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

Out put:- New String=\

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜