Raghunath
Raghunath

Reputation: 614

How to represent backslash

I want to replace which is not in provided list

[^-\\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}:;<,>.?/ ]

I want to include backslash \ in this list, so that backslash wont be replaced. If I give like this

.replaceAll("[^-\\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}\\:;<,>.?/ ]","")

its not working as I expected.

"xyda\asff"..replaceAll("[^-\\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}\\:;<,>.?/ ]","")

Expected result :: xyda\asff
Output :: xydaasff

I dont want to replace \.

Upvotes: 2

Views: 377

Answers (4)

Bohemian
Bohemian

Reputation: 425053

To code a single literal backslash in regex, you need four backslashes (\\\\) in the code (see last char):

[^-\\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}:;<,>.?/ \\\\]

Each pair of backslashes is a single backslash in the string, and you need two of those so it is further escaped in the regex; you need to escape the escape.


Will we ever escape this coding eyesore in java? (trying hard for the pun there)

Upvotes: 3

Affe
Affe

Reputation: 47984

To have a literal backslash in a java regex that is supplied as a string literal in code, you need FOUR backslashes.

\\\\

This is because you want \\ to be in the actual regex, but the compiler also looks at \ as an escape for the string literal, so you need to escape each one again to get it through into the actual string at runtime!

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500785

You need to apply two levels of escaping - one for the regex itself, and one for a Java string literal. That means you need four backslashes in a row. So:

replaceAll("[^-\\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}\\:;<,>.?/\\\\ ]", "")

I assume the \\d was meant to cover any digit, rather than actually putting d in the list?

You may find it easiest to print out your pattern to the console, so you can see exactly what the regex engine sees, without Java string literal escaping being relevant. The above pattern is:

[^-\dA-Za-zÂÃâ`~!@#$%^&*()_+=[{]}\:;<,>.?/\\ ]

So the bits with backslashes are:

  • \d (digit)
  • \: (colon)
  • \\ (backslash)

Upvotes: 4

MadProgrammer
MadProgrammer

Reputation: 347234

You need to escape the slash using another slash. So \ becomes \\

For regular expressions I believe you need to escape it again...

.replaceAll("[^-\\dA-Za-zÂÃâ~!@#$%^&*()_+=[{]}\\:;<,>.?/ ]","")
                ^^                            ^^

If you need to include the \ slash as well, you will need to escape it like \\\\

Upvotes: 1

Related Questions