简体   繁体   English

如何在Java中为带括号的字符串编写正则表达式?

[英]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 我试图解析Java中的C语言代码,并且遇到如下语句

printf("hello world");

I was using Pattern.compile("printf/(/".*/"/)"); 我正在使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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