Java 点不匹配 'any character'

标签 java regex string url replace

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

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

输出:http://wikipedia.org

最佳答案

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

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

这里是来自Java源代码,方法.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 点不匹配 'any character',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365667/

相关文章:

c - 包含字符串的结构体的初始化

java - 如何从一串数字中获取数值?

java - 如何使我的代码从菜单代码中的一个空白变为另一个空白,并使其随机生成输入?

java - 获取 Java Swing 组件的内容

javascript - 如何在 JavaScript 中使用 RegExp 提取字符串?

javascript - 使用正则表达式 replace() 方法一步删除定界符并将第一个字母大写

python - 如何操作列表

java - 无法弄清楚如何使用 isAnimationFinished() 方法(LibGDX)

java - 来自命令行工具的 WADL2JAVA JClass 名称为空错误

regex - 如何否定反向引用正则表达式