Java 将问号(?)替换为(\ \?)
我试图定义一个模式来匹配文本中带有问号(?)的文本。在正则表达式中,问号被认为是“一次或根本不”那么我可以用(\\?)替换文本中的(?)符号来解决模式问题吗?Java 将问号(?)替换为(\ \?),java,regex,replace,escaping,Java,Regex,Replace,Escaping,我试图定义一个模式来匹配文本中带有问号(?)的文本。在正则表达式中,问号被认为是“一次或根本不”那么我可以用(\\?)替换文本中的(?)符号来解决模式问题吗? 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." );
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" );
您还可以使用模式
类的quote
方法来引用regex元字符,这样您就不必担心引用它们了:
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." );
是的,对不起,这就是我的意思。。。我需要换新的吗?与\\?在正则表达式中。@Downvoter:我很想知道你认为不正确的是什么。看起来链接共享(参见)不再有效。页面显示“未找到解决方案”,我不知道我是否会说这是“正确的方法”。如果您的模式是(为了参数起见)“?*\+*?”,其中奇数字符是文字,该怎么办。您希望在代码中看到“\\?*\\\\+\*?”还是[[Pattern.quote(“?”+”+“+Pattern.quote(“\\”+”+“+Pattern.quote(“+”+”?”])?也就是说,我同意使用Pattern.quote可以很容易地被描述为正则表达式中最不容易出错的转义文本的方法。如果它是某种可以更改的字符串,我肯定会使用Pattern.quote(),如果它是外部表达式的一部分,或者只有一个字符的引号,我只会转义它。在原来的问题中,Brad需要引用一个字符串,而不是一个字符。