-2

I was wondering what's wrong with my regular expressions.I was trying to remove certain characters in a string with this code

array[i] = array[i].replaceAll("[.,;:?!\"')\\(]","");

Everything works except for the \ character, it wasn't removed from string. Also I tried this code

array[i] = array[i].replaceAll("[.,;:?!\"')(\\]","");

and it gave me an error.

What am I doing wrong?

9
  • Try: array[i] = array[i].replaceAll("[.,;:?!\\\"')(\]",""); Commented Jul 20, 2015 at 4:32
  • still won't work bro Commented Jul 20, 2015 at 4:33
  • @newbie whats the error? Commented Jul 20, 2015 at 4:34
  • @newbie that shouldn't give an error, what's the error? Commented Jul 20, 2015 at 4:35
  • with his suggestion, no error but it still won't delete the \ Commented Jul 20, 2015 at 4:36

1 Answer 1

1

Try the following RegEx:

array[i] = array[i].replaceAll("[.,;:?!\\\\\"')(]","");

To match a single \ in java, you need to use \\ for every backslash. You need a total of four to match \\ or a \. Hope that doesn't confuse you. This would match:

What is is | What Java thinks it is | What is actually is
,          | ,                      | ,
;          | ;                      | ;
:          | :                      | :
?          | ?                      | ?
!          | !                      | !
\\\\       | \\                     | \
\"         | "                      | "
'          | '                      | '
)          | )                      | )
(          | (                      | (

As you see in the above chart, it can be confusing with all the backslashes in Java RegExes, I really don't know a better solution but to count them out (this one matches with that one, this with that, etc.).

Sign up to request clarification or add additional context in comments.

3 Comments

@AvinashRaj I originally proposed ~3 minutes earlier, it's no problem
Solution in the above comment won't work.
@AvinashRaj originally proposed. I didn't think he wanted to match \ at first ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.