2012-02-16 96 views
0

我有一个文件,它由诸如如何拆分字符串并提取特定元素?

20 19:0.26 85:0.36 1064:0.236 # 750 

我已经能够由线,并将其输出到控制台线读取它线。但是,我真正需要的是从每行中提取诸如“19:0.26”“85:0.36”之类的元素,并对它们执行某些操作。如何分割线条并获取我想要的元素。

+0

需要1064:0.36也? – sgowd 2012-02-16 17:58:14

+0

是在这种情况下的分隔符空白? – 2012-02-16 18:00:50

回答

2

使用正则表达式:

Pattern.compile("\\d+:\\d+\\.\\d+"); 

然后你可以从这个模式最终创建一个Matcher对象使用它的方法find()

0

解析一行数据在很大程度上依赖于数据是什么样的,以及如何一致的是。单纯从您的示例数据和“元素,如”你别说,这可能是那么容易,因为

String[] parts = line.split(" "); 
0

修改该代码,按照你的,

public class JavaStringSplitExample{ 

    public static void main(String args[]){ 

    String str = "one-two-three"; 
    String[] temp; 

    /* delimiter */ 
    String delimiter = "-"; 
    /* given string will be split by the argument delimiter provided. */ 
    temp = str.split(delimiter); 
    /* print substrings */ 
    for(int i =0; i < temp.length ; i++) 
    System.out.println(temp[i]); 

    /* 
    IMPORTANT : Some special characters need to be escaped while providing them as 
    delimiters like "." and "|". 
    */ 

    System.out.println(""); 
    str = "one.two.three"; 
    delimiter = "\\."; 
    temp = str.split(delimiter); 
    for(int i =0; i < temp.length ; i++) 
    System.out.println(temp[i]); 

    /* 
    Using second argument in the String.split() method, we can control the maximum 
    number of substrings generated by splitting a string. 
    */ 

    System.out.println(""); 
    temp = str.split(delimiter,2); 
    for(int i =0; i < temp.length ; i++) 
    System.out.println(temp[i]); 

    } 

}