用(\\?)替换问号(?)

我试图定义一个模式来匹配文本与其中的问号(?)。 在正则表达式中,问号被认为是“一次或根本没有”。 那么我可以用(\\?)替换我的文本中的(?)符号来修复模式问题吗?

String text = "aaa aspx?pubid=222 zzz"; Pattern p = Pattern.compile( "aspx?pubid=222" ); Matcher m = p.matcher( text ); if ( m.find() ) System.out.print( "Found it." ); else System.out.print( "Didn't find it." ); // Always prints. 

你需要逃脱? 作为\\?正则表达式而不是在文本中

 Pattern p = Pattern.compile( "aspx\\?pubid=222" ); 

看见

您还可以使用Pattern类的quote方法来引用正则表达式元字符,这样就不必担心引用它们:

 Pattern p = Pattern.compile(Pattern.quote("aspx?pubid=222")); 

看见

在java中转义正则表达式的任何文本的正确方法是使用:

 String quotedText = Pattern.quote("any text goes here !?@ #593 ++ { ["); 

然后,您可以使用quotedText作为正则表达式的一部分。
例如,您的代码应如下所示:

 String text = "aaa aspx?pubid=222 zzz"; String quotedText = Pattern.quote( "aspx?pubid=222" ); Pattern p = Pattern.compile( quotedText ); Matcher m = p.matcher( text ); if ( m.find() ) System.out.print( "Found it." ); // This gets printed else System.out.print( "Didn't find it." );