Replace a question mark (?) with (\\\\?)

巧了我就是萌 提交于 2019-12-04 23:49:22

You need to escape ? as \\? in the regular expression and not in the text.

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

See it

You can also make use of quote method of the Pattern class to quote the regex meta-characters, this way you need not have to worry about quoting them:

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

See it

The right way to escape any text for Regular Expression in java is to use:

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

Then you can use the quotedText as part of the regular expression.
For example you code should look like:

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." ); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!