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

2019-04-18 00:37发布

问题:

I am trying to define a pattern to match text with a question mark (?) inside it. In the regex the question mark is considered a 'once or not at all'. So can i replace the (?) sign in my text with (\\?) to fix the pattern problem ?

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.

回答1:

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



回答2:

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." );