用(\\?)替换问号(?) [英] Replace a question mark (?) with (\\?)

查看:221
本文介绍了用(\\?)替换问号(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个模式以匹配文本中的问号(?)。在正则表达式中,问号被认为是一次或完全没有。 那么我可以用(\\?)来替换文本中的(?)号来修复模式问题吗?

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.


推荐答案

你需要逃避?在 正则表达式中 \\?而不是文本

You need to escape ? as \\? in the regular expression and not in the text.

Pattern p = Pattern.compile( "aspx\\?pubid=222" );

查看

您还可以使用报价 Pattern 类引用正则表达式元字符的方法,这种方式 无需担心引用他们:

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

查看

这篇关于用(\\?)替换问号(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆