如何在java中提取特定的字符串?

时间:2014-03-30 14:15:48

标签: java substring

我的文本文件包含数据,我应该只从中提取ISDN字符串。 ISDN不断重复,它的价值也在不断变化。我得到的输出只有2个方括号(" []")并且输入文件中没有方括号。

这是输入文本文件

CDR MOC={
   RecordType=0(MOC)
   sequenceNumber=5346435
   callingIMSI=40589345341354118911
   callingIMEI=80FC64634440F
   callingNumber{
      AddInd=H'134
      NumPlan=H'245
      ISDN=45645734
   }

这是我的代码

public class MyFile {

    private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");

    public List<String> getISDNsFromFile(final String fileName)
            throws IOException {
        final Path path = Paths.get(fileName);
        final List<String> ret = new ArrayList<>();

        Matcher m;
        String line;

        try (
                final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);) {
            while ((line = reader.readLine()) != null) {
                m = ISDN.matcher(line);
                if (m.matches()) {
                    ret.add(m.group(1));
                }
            }
        }

        return ret;
    }

    public void writeTextFile(String filename, List<String> s) {
        FileWriter output = null;
        try {
            output = new FileWriter(filename);
            try (BufferedWriter writer = new BufferedWriter(output)) {
                String ss = String.valueOf(s);
                writer.append(ss);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (output != null) {
                try {
                    output.flush();
                    output.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

你的行在开头有空格,因此正则表达式与行不匹配。因此,您得到一个空列表。

在应用正则表达式之前输入

trim(),或者改为使用\s*ISDN=(.*)

答案 1 :(得分:1)

为什么不使用这个正则表达式:

ISDN=(\d+)

第1组将包含ISDN号码。

在java中,使用:

ISDN=(\\d+)

代码:

String s = "CDR MOC={" + "\r\n" +
"RecordType=0(MOC)" + "\r\n" +
"sequenceNumber=5346435" + "\r\n" +
"callingIMSI=40589345341354118911" + "\r\n" +
"callingIMEI=80FC64634440F" + "\r\n" +
"callingNumber{" + "\r\n" +
"AddInd=H'134" + "\r\n" +
"NumPlan=H'245" + "\r\n" +
"ISDN=45645734" + "\r\n" +
"}";
    Pattern p = Pattern.compile("ISDN=(\\d+)");
    Matcher m = p.matcher(s);
    while(m.find()) {
    System.out.println(m.group(1));
}

演示:http://ideone.com/KKUo56