Raf*_*mal 3 java regex string url replace
点应匹配任何字符.那么为什么这个正则表达式不起作用呢?
String url = "http://wikipedia.org";
System.out.println(url.replace("htt.://", ""));
Run Code Online (Sandbox Code Playgroud)
输出: http://wikipedia.org
Uni*_*ron 10
String.replace()编译文字正则表达式.你应该使用String.replaceAll()或String.replaceFirst():
String url = "http://wikipedia.org";
System.out.println(url.replaceFirst("htt.://", ""));
Run Code Online (Sandbox Code Playgroud)
这里是来自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()));
}
Run Code Online (Sandbox Code Playgroud)
你正在使用replace()方法.它需要一个字符串而不是一个正则表达式你可以使用replaceAll();它采取这样的正则表达式:replaceAll("htt.://", "");
您需要使用replaceAll()将第一个参数解释为正则表达式.
String url = "http://wikipedia.org";
System.out.println(url.replaceAll("htt.://", ""));
Run Code Online (Sandbox Code Playgroud)
输出
wikipedia.org
但有一句话:我假设你正在试图制作两者http并https与你的正则表达式一起工作.你现在拥有它的方式是行不通的,因为在"https"的情况下,它只需要1个字符而不是2个字符.为了弥补这一点,请使用
url.replaceAll("htt.*://", "")
Run Code Online (Sandbox Code Playgroud)