点应该匹配任何字符。那么为什么这个正则表达式不起作用?
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/