43423

How to represent backslash

Question:

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ÂÃâ`~!@#$%^&*()_+=[{]}\\:;<,>.?/ ]","") <hr />Expected result :: xyda\asff Output :: xydaasff

I dont want to replace \.

Answer1:

To code a single literal backslash in regex, you need <em>four</em> 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.

<hr />

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

Answer2:

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

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

I assume the \\d was meant to cover any digit, rather than <em>actually</em> 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:

<ul><li>\d (digit)</li> <li>\: (colon)</li> <li>\\ (backslash)</li> </ul>

Answer3:

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 \\\\

Answer4:

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!

Recommend

  • nested Python numpy arrays dimension confusion
  • JPA Criteria : in clause with many columns
  • Java - Sort one array based on values of another array?
  • Generating key-value pairs from field, using jQuery
  • Hibernate: How declare foreign key without having to code association methods in the domain object?
  • Needs help for Genetic Algorithm Single-Point Crossover Mechanism in Java
  • Numpy: 2D array access with 2D array of indices
  • How to select sub-strings based on the presence of word pairs? Python
  • Substitute partial line in vim using only substitute command
  • Checking for a dictionary key which is a range of integers
  • Select document having particular key value pair but not having other key value pair
  • Need help writing prop to blak :: Sudoku → [Pos] (Haskell)
  • Asking SslStream to accept ONLY a certificate signed by a particular public key
  • Passing unspecialized template as a template parameter
  • Deploying pre-encrypted configuration files to a production environment
  • Each Radiobutton for each form or 1 Form for all radiobuttons?
  • What does a hyphen at end of a term mean
  • Deduce parent class of inherited method in C++
  • Use sed with regex and (
  • Find group of records that match multiple values
  • Hide HTML elements without javascript, only CSS
  • Transactional Create with Validation in ServiceStack Redis Client
  • PHP buffered output depending on server setting?
  • Functions in global context
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Is possible to count alias result on mysql
  • Check if a string to interpolate provides expected placeholders
  • Redux, normalised entities and lodash merge
  • Do create extension work in single-user mode in postgres?
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • AngularJs get employee from factory
  • Acquiring multiple attributes from .xml file in c#
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • apache spark aggregate function using min value
  • How can I remove ASP.NET Designer.cs files?
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal