Java 如何使用正则表达式提取此参数
我需要提取这个 例如:Java 如何使用正则表达式提取此参数,java,regex,Java,Regex,我需要提取这个 例如: www.google.com maps.google.com maps.maps.google.com 我需要从中提取google.com 我如何在Java中做到这一点 String str="www.google.com"; try{ System.out.println(str.substring(str.lastIndexOf(".", str.lastIndexOf(".") - 1) + 1)); }catch(ArrayInde
www.google.com
maps.google.com
maps.maps.google.com
我需要从中提取google.com
我如何在Java中做到这一点
String str="www.google.com";
try{
System.out.println(str.substring(str.lastIndexOf(".", str.lastIndexOf(".") - 1) + 1));
}catch(ArrayIndexOutOfBoundsException ex){
//handle it
}
Pattern pat = Pattern.compile( ".*\\.([^.]+\\.[^.]+)" ) ;
Matcher mat = pat.matcher( "maps.google.com" ) ;
if( mat.find() ) {
System.out.println( mat.group( 1 ) ) ;
}
如果是相反的方式,并且您想要除域的最后两部分之外的所有内容(在您的示例中;www、maps和maps.maps
),则只需将第一行更改为:
Pattern pat = Pattern.compile( "(.*)\\.[^.]+\\.[^.]+" ) ;
假设要从主机名中获取顶级域,可以尝试以下操作:
Pattern pat = Pattern.compile( ".*\\.([^.]+\\.[^.]+)" ) ;
Matcher mat = pat.matcher( "maps.google.com" ) ;
if( mat.find() ) {
System.out.println( mat.group( 1 ) ) ;
}
如果是相反的方式,并且您想要除域的最后两部分之外的所有内容(在您的示例中;www、maps和maps.maps
),则只需将第一行更改为:
Pattern pat = Pattern.compile( "(.*)\\.[^.]+\\.[^.]+" ) ;
在
上拆分,然后选择最后两位
String s = "maps.google.com";
String[] arr = s.split("\\.");
//should check the size of arr here
System.out.println(arr[arr.length-2] + '.' + arr[arr.length-1]);
在
上拆分,然后选择最后两位
String s = "maps.google.com";
String[] arr = s.split("\\.");
//should check the size of arr here
System.out.println(arr[arr.length-2] + '.' + arr[arr.length-1]);
从字符串中提取已知的子字符串没有多大意义;)你为什么要这么做
String result = address.replaceAll("^.*google.com$", "$1");
当这相等时:
String result = "google.com";
如果需要测试,请尝试:
如果您需要谷歌地址的其他部分,这可能会有帮助:
String googleSubDomain = address.replaceAll(".google.com", "");
(提示-第一行代码可以解决您的问题!)从字符串中提取已知子字符串没有多大意义;)你为什么要这么做
String result = address.replaceAll("^.*google.com$", "$1");
当这相等时:
String result = "google.com";
如果需要测试,请尝试:
如果您需要谷歌地址的其他部分,这可能会有帮助:
String googleSubDomain = address.replaceAll(".google.com", "");
(提示-第一行代码可以解决您的问题!)您想提取
google.com
,还是域名的前两级?您想提取google.com
,还是域名的前两级?