简体   繁体   中英

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.

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

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