Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. 
like image 496
Brad Avatar asked Dec 29 '10 14:12

Brad


People also ask

What should I replace question mark with?

Which number will replace the question mark ? Hence the number -1 will replace the question mark.

Which letter will replace the question mark (?) In the given series?

Hence, N replaces question mark. Was this answer helpful?

What does a question mark (?) Designate?

A question mark (?) is a punctuation symbol placed at the end of a sentence or phrase to indicate a direct question, as in: She asked, "Are you happy to be home?" The question mark is also called an interrogation point, note of interrogation, or question point.


2 Answers

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

like image 86
codaddict Avatar answered Oct 04 '22 13:10

codaddict


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." );  
like image 45
m_vitaly Avatar answered Oct 04 '22 12:10

m_vitaly