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.
Which number will replace the question mark ? Hence the number -1 will replace the question mark.
Hence, N replaces question mark. Was this answer helpful?
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.
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." );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With