【发布时间】:2016-07-21 17:46:17
【问题描述】:
我正在使用的一些字符串模式在运行时没有为我获取匹配项,而当我在线使用正则表达式检查器(例如 Regular Expression Tester)时,我看到我的模式获取了我想要的输出。
public class RegexMatches
{
public static void main( String args[] ){
String input = "[1463895254]PING www.andi.dz (213.179.181.44) 100(128) bytes of data.[1463895254]108 bytes from 213.179.181.44: icmp_seq=1 ttl=54 time=195 ms[1463895255]108 bytes from 213.179.181.44: icmp_seq=2 ttl=54 time=202 ms[1463895256]108 bytes from 213.179.181.44: icmp_seq=3 ttl=54 time=180 ms[1463895257]108 bytes from 213.179.181.44: icmp_seq=4 ttl=54 time=200 ms[1463895258]108 bytes from 213.179.181.44: icmp_seq=5 ttl=54 time=206 ms[1463895259]108 bytes from 213.179.181.44: icmp_seq=6 ttl=54 time=188 ms[1463895260]108 bytes from 213.179.181.44: icmp_seq=7 ttl=54 time=182 ms[1463895261]108 bytes from 213.179.181.44: icmp_seq=8 ttl=54 time=223 ms[1463895263]108 bytes from 213.179.181.44: icmp_seq=9 ttl=54 time=187 ms[1463895263]108 bytes from 213.179.181.44: icmp_seq=10 ttl=54 time=199 ms";
try{
String op[] = parseIndividualIP(input);
System.out.println(op[1]);
System.out.println(op[8]);
}
catch (Exception e){
e.printStackTrace();
}
}
// Doesn't Work...
public static String[] parseIndividualIP(String input) throws IPAddressNotFoundException {
// Capture the ip-address after 'x byes from'
Pattern p = Pattern.compile("bytes\\s+from\\s+([\\d,\\.]+):");
Matcher m = p.matcher(input);
if (m.find()){
int i = 0;
String[] s = new String[10];
while(m.find()){
s[i] = m.group(++i);
}
return s;
}
else
throw new IPAddressNotFoundException();
}
}
我不知道为什么在运行时我没有匹配项以及我应该如何调试这个问题。因为在运行前后对模式进行了交叉检查。
输入字符串 -
[1463895254]PING www.andi.dz (213.179.181.44) 100(128) bytes of data.[1463895254]108 bytes from 213.179.181.44: icmp_seq=1 ttl=54 time=195 ms[1463895255]108 bytes from 213.179.181.44: icmp_seq=2 ttl=54 time=202 ms[1463895256]108 bytes from 213.179.181.44: icmp_seq=3 ttl=54 time=180 ms[1463895257]108 bytes from 213.179.181.44: icmp_seq=4 ttl=54 time=200 ms[1463895258]108 bytes from 213.179.181.44: icmp_seq=5 ttl=54 time=206 ms[1463895259]108 bytes from 213.179.181.44: icmp_seq=6 ttl=54 time=188 ms[1463895260]108 bytes from 213.179.181.44: icmp_seq=7 ttl=54 time=182 ms[1463895261]108 bytes from 213.179.181.44: icmp_seq=8 ttl=54 time=223 ms[1463895263]108 bytes from 213.179.181.44: icmp_seq=9 ttl=54 time=187 ms[1463895263]108 bytes from 213.179.181.44: icmp_seq=10 ttl=54 time=199 ms
使用的正则表达式模式 -
bytes\\s+from\\s+([\\d,\\.]+):
【问题讨论】:
-
if (m.find()){- >while (m.find()){,不需要使用嵌套的m.find