Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping '{' when regex-ing in java?

I'm trying to get my code to ignore some some lines it's reading. My SSCE is thus:

public class testRegex {
    private static final String DELETE_REGEX = "\\{\"delete"; //escape the '{', escape the ' " '
    private static final String JSON_FILE_NAME = "example";
public static void main(String[] args){
    String line = null;
    try{
        BufferedReader buff = new BufferedReader (new FileReader(JSON_FILE_NAME + ".json"));
        line = buff.readLine        buff.close();
        }catch (FileNotFoundException e){e.printStackTrace();}
         catch (IOException e){e.printStackTrace();}
    String line=buff.readLine();
    System.out.println(line.contains(DELETE_REGEX));
    }
}

My file only contains the line:

{"delete":{"status":{"user_id_str":"123456789","user_id":123456789,"id_str":"987654321","id":987654321}}}

But this prints out false...is my regex wrong? I'm matching { by double escaping it with \\{ as it advises here.

The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

And I escape the " by using \".

So how can I fix my program?

*p.s. I've tried manually inputting line = "\{\"delete" (no need to double escape as line is a string not a regex), and I get the same result.

like image 567
AncientSwordRage Avatar asked Mar 01 '26 07:03

AncientSwordRage


2 Answers

String.contains() performs an exact match, not a regex search. Do not escape the { brace.

like image 198
Sean Patrick Floyd Avatar answered Mar 04 '26 06:03

Sean Patrick Floyd


The contains method doesn't take a regex as parameter so you don't have to escape the {.

Simply do

line.contains("{\"delete")
like image 30
Denys Séguret Avatar answered Mar 04 '26 08:03

Denys Séguret