如何在Java中从单个长字符串中提取IP地址

如何在Java中从单个长字符串中提取IP地址,java,android,string,ip-address,android-logcat,Java,Android,String,Ip Address,Android Logcat,我正在编写一个android应用程序来执行traceroute命令 现在,当traceroute执行时,它将控制台输出放入一个很长的字符串中。这是通过以下代码完成的: public void runAsRoot(String[] cmds) throws Exception { Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOut

我正在编写一个android应用程序来执行traceroute命令

现在,当traceroute执行时,它将控制台输出放入一个很长的字符串中。这是通过以下代码完成的:

    public void runAsRoot(String[] cmds) throws Exception {


    Process p = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(p.getOutputStream());
    InputStream is = p.getInputStream();
    for (String tmpCmd : cmds) {
        os.writeBytes(tmpCmd+"\n");
        int readed = 0;
        byte[] buff = new byte[4096];

        // if cmd requires an output
        // due to the blocking behaviour of read(...)
        boolean cmdRequiresAnOutput = true;
        if (cmdRequiresAnOutput) {
            while( is.available() <= 0) {
                try { Thread.sleep(10000); } catch(Exception ex) {}  //timeout.. gotta watch this carefully.
            }

            while( is.available() > 0) {

                readed = is.read(buff);
                if ( readed <= 0 ) break;
                String seg = new String(buff,0,readed);
                System.out.println("#> "+seg);
                ListofIPs = seg;


            }
        }
    }        
    os.writeBytes("exit\n");
    os.flush();
}
public void runAsRoot(字符串[]cmds)引发异常{
进程p=Runtime.getRuntime().exec(“su”);
DataOutputStream os=新的DataOutputStream(p.getOutputStream());
InputStream is=p.getInputStream();
用于(字符串tmpCmd:cmds){
os.writeBytes(tmpCmd+“\n”);
int readed=0;
字节[]buff=新字节[4096];
//如果cmd需要输出
//由于读取的阻塞行为(…)
布尔值CmdRequiresAnutput=true;
如果(CmdRequiremesOnutput){
while(is.available()0){
readed=is.read(buff);

如果(readed我会尝试删除第一行,然后尝试按空格使用。这样你就知道IP位于1,5,9,…
(1+4*n_迭代)
,或者你可以按“ms”拆分,然后再按空格拆分。

试试

在您的情况下,代码如下所示:

seg.split("[^((\d{1,3}\.){3}\d{1,3}]");

我没有测试它,但它应该可以完成这项工作。您可以立即修补一个更优雅的解决方案。

看看
字符串
类的
.split()
方法。您熟悉正则表达式吗?如果不熟悉,请检查这里,这正是您所需要的:逐行阅读..使用
.split(“”)
第二个元素是IP地址。这会不会删除IP,剩下的就留给我了?不会,因为我添加了[^…],这不是这个意思。基本上,这有点老套:表达式是除IP之外的所有元素,IP将是您的数组元素。