Java点不匹配“任何字符" [英] Java dot doesn't match 'any character'

查看:36
本文介绍了Java点不匹配“任何字符"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点应该匹配任何字符.那么为什么这个正则表达式不起作用?

Dot should match any character. So why doesn't this regex work?

String url = "http://wikipedia.org";
System.out.println(url.replace("htt.://", ""));

输出:http://wikipedia.org

推荐答案

String.replace() 编译一个文字正则表达式.你应该使用 String.replaceAll()String.replaceFirst():

String.replace() compiles a literal regex. You ought to use String.replaceAll() or String.replaceFirst():

String url = "http://wikipedia.org";
System.out.println(url.replaceFirst("htt.://", ""));

这里来自Java源代码,方法.replace():

Here is from the Java source code, the method .replace():

/**
 * Replaces each substring of this string that matches the literal target
 * sequence with the specified literal replacement sequence. The
 * replacement proceeds from the beginning of the string to the end, for
 * example, replacing "aa" with "b" in the string "aaa" will result in
 * "ba" rather than "ab".
 *
 * @param  target The sequence of char values to be replaced
 * @param  replacement The replacement sequence of char values
 * @return  The resulting string
 * @throws NullPointerException if <code>target</code> or
 *         <code>replacement</code> is <code>null</code>.
 * @since 1.5
 */
public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

这篇关于Java点不匹配“任何字符"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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