簡體   English   中英

用(\\?)替換問號(?)

[英]Replace a question mark (?) with (\\?)

我試圖定義一個模式來匹配文本與其中的問號(?)。 在正則表達式中,問號被認為是“一次或根本沒有”。 那么我可以用(\\\\?)替換我的文本中的(?)符號來修復模式問題嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM