将问号 (?) 替换为 (\\?)
我正在尝试定义一个模式来匹配文本中带有问号(?)的文本。在正则表达式中,问号被认为是“一次或根本不”。 那么我可以用 (\\?) 替换文本中的 (?) 符号来解决模式问题吗?
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在正则表达式中将
?
转义为\\?
,而不是在文本中。查看
您还可以使用
quote
Pattern
类的方法来引用正则表达式元字符,这样您不必担心引用它们:查看
You need to escape
?
as\\?
in the regular expression and not in the text.See it
You can also make use of
quote
method of thePattern
class to quote the regex meta-characters, this way you need not have to worry about quoting them:See it
在java中转义正则表达式任何文本的正确方法是使用:
然后您可以使用quotedText作为正则表达式的一部分。
例如,您的代码应如下所示:
The right way to escape any text for Regular Expression in java is to use:
Then you can use the quotedText as part of the regular expression.
For example you code should look like: