日期:2014-05-20 浏览次数:20898 次
import java.io.*; import java.util.regex.*; public class ResolveFile { public static void main(String[] args) { resolveFile("c:/test.txt"); //我把你的测试存入到此文件,并去除空白符,每一条目占一行 } public static void resolveFile(String fileName){ BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileName)); String string; while ((string = br.readLine()) != null) { resolveLine(string);//读取一行,并解释一行 } } catch (IOException e) { throw new RuntimeException(e); } finally { if (br != null) try { br.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public static void resolveLine(String sourceString){ String regex = "^([A-Za-z0-9\\-_()\\s]+?)[:]([A-Za-z][A-Za-z0-9]*?)[\\-_](STM[0-9\\-#:]+?[\\d]+)[\\-]([A-Za-z0-9\\-_()\\s]+?)[:]([A-Za-z][A-Za-z0-9]*?)[\\-_](STM[0-9\\-#:]+?[\\d]+)$"; Matcher matcher = Pattern.compile(regex).matcher(sourceString);// while(matcher.find()){ //将每一行解释出的两个设备相关信息打印出来 System.out.println(matcher.group());//所有信息 System.out.println(matcher.group(1));//设备1名称 System.out.println(matcher.group(2));//设备1插槽 System.out.println(matcher.group(3));//设备1端口 System.out.println(matcher.group(4));//设备2名称 System.out.println(matcher.group(5));//设备2插槽 System.out.println(matcher.group(6));//设备2端口 } } } /*output: bsfgs:A1-STM-4#1-BSB:I5-STM-4#1 bsfgs A1 STM-4#1 BSB I5 STM-4#1 KM-DZH 155_7470:MS_STM1:1-SD2:I7-STM-1#5 KM-DZH 155_7470 MS STM1:1 SD2 I7 STM-1#5 DZDD:I6-STM-1#1-DZH-KM 155_7470:MS_STM1:1 DZDD I6 STM-1#1 DZH-KM 155_7470 MS STM1:1 SD:I6-STM-1#11-4LOU-155M(HUAWEI-wantong):MS_STM1:1 SD I6 STM-1#11 4LOU-155M(HUAWEI-wantong) MS STM1:1 */