今天碰到个问题:我的系统里面有个地方要导入银行返回的数据,但是这些数据可能不合乎规则,因此,我需要对数据进行进行扫描,然后才能读入程序,存入数据库.因此我想到了java.util.Scanner类.
D:/a.txt
003000000102123456789 000009000.00A
002000000102123456 000002000.00A
代码
import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("D:/detail-2008122.txt"));
String pattern = "(\\w{3})" + "(\\w{7})" + "(\\w{2})" + "(.{21})"
+ "(\\w{9}[.]\\w{2})" + "([A-Z])";
scanner.useDelimiter("\r");
while (scanner.hasNext(pattern)) {
scanner.next(pattern);
MatchResult match = scanner.match();
String store_no = match.group(1);
System.out.println("*" + store_no + "*");
String cus_no = match.group(2);
System.out.println(cus_no);
String bank_no = match.group(3);
System.out.println(bank_no);
String account_no = match.group(4);
System.out.println(account_no);
String money = match.group(5);
System.out.println(money);
String deduct_no = match.group(6);
System.out.println(deduct_no);
}
}
}
因为文件里面的数据里有空格,但是这些空格是有意义的,不能去掉,所以如果不设scanner.useDelimiter("\r");的话,会默认将空格做为定界符,那样会永远匹配不成功!