2

I need to define an array containing below all special characters..

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \

I am using this

List<String> specialCharactersInSolr = Arrays.asList(new String[] {
                "+", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^",
                "~", "*", "?", ":", });

It is accepting all the character except " and \

Please help how to define these two as well.

7
  • 3
    just escape them with a backslash! And why are you not using Character instead of String? Commented Jul 12, 2013 at 10:25
  • Exactly what I was about to type! Commented Jul 12, 2013 at 10:26
  • 1
    Use "\"" and "\\" respectively. But you say you want characters here and define strings instead? Commented Jul 12, 2013 at 10:26
  • @jlordo. Probably because he also needs to store - && and ||. Commented Jul 12, 2013 at 10:26
  • 3
    In Java 5+ you do not need new String[] { ... }. Commented Jul 12, 2013 at 10:26

2 Answers 2

10

\ and " are special characters in String class

  • " is start or end of String
  • \ is used to create some characters like new lines \n \r tab\t or to escape special characters like in your case \ and "

So to make them literals you will have to escape them with "\\" and "\""


Other idea is to use Character[] instead of String[] so you wont have to escape " and yours characters can be written as '"' or '\\' (because ' require escaping - it should be written as '\'' - \ is also special here and will also require escaping to produce its literal).

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

7 Comments

And in turn escape the backslashes as well.
@RohitJain this ain't regex. double backslash is how you write a single backslash
@RohitJain you are mistaken this will work fine.Try it your self
@Bohemian. Ah! right. Mixed it up with regex. Sorry. It'll work fine.
Ya i m not so active. But now i am trying to accept it. But it is not click able.
|
4

Use this

List<String> specialCharactersInSolr = Arrays.asList(new String[]{
            "+", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^",
            "~", "*", "?", ":","\"","\\"});

here "\"" and "\\" are for " and \

2 Comments

Won't work. You need to escape the backslashes as well. This has to be done in Java.
@RohitJain wrong. this above code is fine. you thinking of how to write a literal backslash in regex maybe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.