我有一个简单的程序,可以查找您提供的 IP 的详细信息,我将向您展示我的一些代码的示例
int regIndex = src.indexOf("Region:") + 16;
int endIndex = src.indexOf("<", regIndex);
String region = src.substring(regIndex, endIndex);
if(regIndex == 15) region = "None";
int counIndex = src.indexOf("Country:") + 17;
int couneIndex = src.indexOf(" <", counIndex);
String country = src.substring(counIndex, couneIndex);
正如您所看到的,这绝对不是最有效的方法。我正在使用的网站提供的信息如下:http://whatismyipaddress.com/ip/1.1.1.1
我以前从未真正使用过正则表达式,但在我看来,可能有一个真正可以使其更高效且更易于编程,但我一直在环顾四周,但我很迷失。
所以基本上我的问题是,我如何使用正则表达式(或者是否有其他更有效的方法)。
任何帮助都会很棒, 谢谢:)
最佳答案
你可以这样做:
String s = "bla Country: Australia <bla";
Pattern pattern = Pattern.compile("Country: (.*) [<]");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println("Country = " + matcher.group(1));
}
关于java - 可能的正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6463922/