62,614
社区成员
发帖
与我相关
我的任务
分享
public static void main(String args[]) {
//Scanner s=new Scanner(input1.txt);
//String str=s.nextLine();
String str="1 chocolate bar at 0.85";
String ID=str.substring(0, str.indexOf(" "));
String name=str.substring(str.indexOf(" ")+1,str.indexOf(" at "));
String price=str.substring(str.lastIndexOf(" ")+1);
System.out.println("ID:"+ID+" name:"+name+" price:"+price);
//s.close;
}
ID:1 name:chocolate bar price:0.85
Matcher match=Pattern.complie("(\\d+) (.*?) at ([0-9\\.])+").match(string);
while(match.find()){
String ID=matcher.group(1);
String name=matcher.group(2);
String price=matcher.group(3);
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "1 book at 12.49\n" +
"1 music CD at 14.99\n" +
"1 chocolate bar at 0.85";
Matcher match = Pattern.compile("(\\d+) ([\\w ]+) at ([0-9\\.]+)").matcher(input);
while (match.find()) {
String ID = match.group(1);
String name = match.group(2);
String price = match.group(3);
System.out.println("id=" + ID + " name=" + name + " price=" + price);
}
}
}
String regex="(\\d+) (.*?) at ([0-9\\.])+";
String regex="(\\d+)\\s(.*?)at\\s([0-9\\.])+";
package temporary;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Teststring {
/**
* @param args
*/
private static BufferedReader bf = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Teststring.execute();
}
public static void execute(){
String ID=null;
String name=null;
float price = 0;
// ArrayList array = new ArrayList();
File f = new File("data.txt");
try {
String regex = "(\\d+)\\s+?(.*?)\\s+?at\\s+?([0-9]+.[0-9]+)";
Pattern pattern = null;
bf = new BufferedReader(new FileReader(f));
String string = null;
while((string=bf.readLine())!=null){
pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
ID = matcher.group(1);
name = matcher.group(2);
price = Float.parseFloat(matcher.group(3));
}
System.out.println("ID == "+ID);
System.out.println("NAME == "+name);
System.out.println("price == "+price);
}
bf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}