【问题标题】:Replace a question mark (?) with (\\?)将问号 (?) 替换为 (\\?)
【发布时间】:2011-06-01 02:00:28
【问题描述】:

我正在尝试定义一个模式来匹配其中带有问号 (?) 的文本。在正则表达式中,问号被认为是“一次或根本没有”。 那么我可以用 (\\?) 替换文本中的 (?) 符号来解决模式问题吗?

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.

【问题讨论】:

    标签: java regex replace escaping


    【解决方案1】:

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

    【讨论】:

    • 我不知道我是否会说这是“正确的方式”。如果你的模式是(为了论证)'?*\+*?'其中奇数字符是文字​​。您更愿意看到“\\?*\\\\+\*?”或 [[ Pattern.quote("?") + "" + Pattern.quote("\\") + "+" + Pattern.quote("") + "?" ]] 在你的代码中?也就是说,我同意使用 Pattern.quote 可以很容易地被描述为最不容易出错的方法来转义正则表达式的文本。
    • 如果它是某种可以改变的字符串,我肯定会使用 Pattern.quote() ,如果这是外部表达式的一部分或一个字符唯一的引号,我会转义它。在最初的问题中,Brad 需要引用一个字符串,而不是一个字符。
    【解决方案2】:

    您需要在正则表达式而不是文本中将?转义为\\?

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

    See it

    你也可以利用Pattern类的quote方法来引用正则表达式的元字符,这样就不用担心了引用他们:

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

    See it

    【讨论】:

    • 是的,对不起,我的意思是……我需要更换 ?和 \\?在正则表达式中。
    • @Downvoter:我很想知道你认为不正确的是什么。
    • 似乎ideone.com 的链接共享(查看)不再有效。页面显示“未找到解决方案”
    猜你喜欢
    • 1970-01-01
    • 2017-09-07
    • 2022-07-21
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多