Java dot does not match “any character”
•
Java
The dot should match any character So why doesn't this regular expression work?
String url = "http://wikipedia.org";
System.out.println(url.replace("htt.://",""));
Output: http://wikipedia.com org
Solution
String. Replace() compiles literal regular expressions You should use string Replaceall() or string replaceFirst():
String url = "http://wikipedia.org";
System.out.println(url.replaceFirst("htt.://",""));
This is a method from Java source code 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()));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
