如何拆分字符串并提取特定元素?
问题描述:
我有一个文件,它由诸如如何拆分字符串并提取特定元素?
20 19:0.26 85:0.36 1064:0.236 # 750
我已经能够由线,并将其输出到控制台线读取它线。但是,我真正需要的是从每行中提取诸如“19:0.26”“85:0.36”之类的元素,并对它们执行某些操作。如何分割线条并获取我想要的元素。
答
使用正则表达式:
Pattern.compile("\\d+:\\d+\\.\\d+");
然后你可以从这个模式最终创建一个Matcher对象使用它的方法find()
。
答
Java字符串split方法,你可以调用
String [] stringArray = "some string".split(" ");
,如果你想这样就可以符合特定字符拆断的,您可以使用正则表达式。
字符串文件: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
模式文件(用于制备正则表达式): http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
答
解析一行数据在很大程度上依赖于数据是什么样的,以及如何一致的是。单纯从您的示例数据和“元素,如”你别说,这可能是那么容易,因为
String[] parts = line.split(" ");
答
修改该代码,按照你的,
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]);
}
}
需要1064:0.36也? – sgowd 2012-02-16 17:58:14
是在这种情况下的分隔符空白? – 2012-02-16 18:00:50