Java正则表达式提取域名?
我需要java正则表达式从字符串中只提取域名 例: 基本上,它应该从URL中删除所有www和https。 请帮忙Java正则表达式提取域名?,java,regex,Java,Regex,我需要java正则表达式从字符串中只提取域名 例: 基本上,它应该从URL中删除所有www和https。 请帮忙 谢谢 如果您对regex感兴趣,可以尝试以下方法: urlString.replaceFirst("^(https?://)?(www\\.)?", "") 然而,正如评论所暗示的那样,这不是一个好主意 要实现这一点,需要两个java类:Matcher和Pattern 您必须构建Pattern对象,并对其调用提供matcher实例的方法 // in the beginning,
谢谢 如果您对regex感兴趣,可以尝试以下方法:
urlString.replaceFirst("^(https?://)?(www\\.)?", "")
然而,正如评论所暗示的那样,这不是一个好主意 要实现这一点,需要两个java类:Matcher和Pattern 您必须构建Pattern对象,并对其调用提供matcher实例的方法
// in the beginning, import necessary classes
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// this is the array with urls to check
String [] urls = {"https://google.com", "www.google.com"};
// now, let's check if strings are matching
for (int i = 0; i < urls.length; i++) {
// string to be scanned to find the pattern
String url = urls[i];
String pattern = "google.com";
// create a Pattern object
Pattern p = Pattern.compile(pattern);
// now, create Matcher object.
Matcher m = p.matcher(url);
// let's check if something was found
if (m.find()) {
System.out.println("Found value: " + url);
} else {
System.out.println("NO MATCH");
}
}
}
}
您可以将希望模式检查的所有URL添加到数组中
.*?\.(.*?\.[a-zA-Z]+)
试试这个。看演示
不要使用正则表达式。你试过什么?你被困在哪里?在您的问题中发布您尝试的正则表达式。Java中有URL类用于此。检查此项我认为OP需要一个更通用的解决方案,该解决方案也适用于google以外的其他域。comit查找并匹配以下字符串:weionheotiwot.w0ioghw0ogiwjgt.wghwoigh
.*?\.(.*?\.[a-zA-Z]+)