krisnik
krisnik

Reputation: 1436

How to write a regex in java for a String with parenthesis?

I am trying to parse a C language code in java and I encountered statements like

printf("hello world");

I was using Pattern.compile("printf/(/".*/"/)"); but was getting an error stating that

/( is not a valid escape sequence

Please give a way to tackle this kind of scenario.

Upvotes: 0

Views: 62

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

To escape a character, you need to use backslash instead of forward slash. Since ( is a special meta character, you need to escape that also.

Pattern.compile("printf\\(\".*?\"\\);");

Example:

String value = "printf(\"hello world\");";
System.out.println(value.matches("printf\\(\".*?\"\\);"));
//=> true

Upvotes: 2

Related Questions