简体   繁体   中英

how to escape escape characters in Java

I have a large file that contains \\' that I need to find. I've tried variations of the following but it's not working:

do{           
       line =  TextFileIO.readLine(bufferedReader);           
       if(line != null){
           TextFileIO.writeLine(bufferedWriter,line); 

           for (int i = 0; i < line.length() - 1; i++){

              if(line.substring(i,i+1).equals("\\\'"))System.out.println("we found it " + line);

           }
        }

    }while (line != null);

No need to escape the single quote!

Single quotes don't need escaping because all Java strings are delimited by double quotes. Single quotes delimit character literals. So in a character literal, you need to escape single quotes, eg '\\'' .

So all you need is "\\\\'" , escaping only the backslash.

substring(i,i+1) cannot produce a two character string. If you are trying to get 2-character strings, you need to call with (i,i+2) .

Also, your for loop can be replaced by a call to contains .

if(line.contains("\\'"))System.out.println("we found it " + line);

To represent a single backslash followed by an apostrophe, you can use

"\\'"

But there is no way substring(i,i+1) can be equal to a two-character string.

Perhaps you mean

if (line.substring(i, i+2).equals("\\'")) ...

line.substring(i,i+1) only contains one character, and the for loop can replaced by line.indexOf("\\\\'") >= 0 :

if (line.indexOf() >= 0) {
    System.out.println("we found it " + line);
}

\\\\ is an escaped \\ in Java, so I think your match string should be "\\\\" .

Ps I'm not exactly sure what you are trying to achieve here, but there appears to be more elegant, more "java-like" ways to do it than what you have here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM