从字符串模式中提取数字

时间:2018-07-17 15:06:24

标签: java string

我有一个文件,其中包含有关称为“泄漏”的参数的详细信息。文件中有一行提供了此信息。 “泄漏”有三种类型;短,中,长。在给定的时间可能不会显示所有泄漏。以下是6个文件中的泄漏信息示例。模式是type_of_leak(number_of_leaks)。

例如:

leak:   short(4)    medium(11)  long(4)
leak:   short(6)
leak:   long(3)
leak:   medium(4)   
leak:   medium(1)   long(8)
leak:   short(1)    long(5)

我想按顺序提取三个泄漏值并填充一个整数数组。第0个元素短漏,第1个元素中漏和第2个元素长漏。如果未显示给定类别的泄漏,则该值应为“ 0”。下面是我正在使用的代码。我的代码可以提取泄漏,但是当泄漏数大于1位数时,它只能提取第一位数。

int[] leaks = new int[3];

if(line.contains("leak:")){ //search for the line that starts with leak

    System.out.println(line);

    //short leaks
    if(line.contains("short")) {
        int index = line.indexOf("short");
        int numShortLeaks = Integer.parseInt((line.substring(index+6, index+7)));
        leaks[0] = numShortLeaks;
    }else {
        leaks[0] = 0; //no short leaks replace with zero                    
    }

    if(line.contains("medium")) {
        int index = line.indexOf("medium");
        int numMediumLeaks = Integer.parseInt((line.substring(index+7, index+8)));
        leaks[1] = numMediumLeaks;
    }else {
        leaks[1] = 0;                       
    }

    if(line.contains("long")) {
        int index = line.indexOf("long");
        int numLongLeaks = Integer.parseInt((line.substring(index+5, index+6)));
        leaks[2] = numLongLeaks;
    }else {
        leaks[2] = 0;                       
    }

2 个答案:

答案 0 :(得分:1)

使用this regular expression

/leak:(?:\s+short\((\d+)\))?(?:\s+medium\((\d+)\))?(?:\s+long\((\d+)\))?

这将分别与组1、2和3中的短,中和长整数匹配。

即使未提供short,medium,long中的一个或多个,组号也将是正确的,因此第3组始终是long值,无论是否提供了short / medium。

String line = "leak:   short(16)    long(3)";
Pattern pattern = Pattern.compile("leak:(?:\\s+short\\((\\d+)\\))?(?:\\s+medium\\((\d+)\\))?(?:\\s+long\\((\\d+)\\))?");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {

  //Stick them in your array.
  System.out.println("short " + matcher.group(1)); //16
  System.out.println("medium " + matcher.group(2)); //null
  System.out.println("long  " + matcher.group(3)); //3
}

答案 1 :(得分:0)

通过示例

  

泄漏:短(4)中(11)长(4)

代码很简单

int leakIndex = line.indexOf("leak:");
if(leakIndex > -1) {
    // Got the data
    // 1. Split by tab to group like short(4) or medium(11) or long(4)
    final String[] dataLine = line.subString(leakIndex + 1, line.length).split("\t");
    // 2. Loop over the data line to extract the value
    for(String data : dataLine) {
        // I suggest you to create a sub function to extract
        // 3. Simple idea is replaced all non number by empty value and we can parse it
        if(data.contains("short")) {
            leaks[0] = Integer.parseInt(data.replaceAll("[^0-9]", ""));
            // TODO: You should handling NumberFormatException here
        } else if() {
        }
        // Do other for medium and long here
} else {
// Skip
}

请注意:通过将一个长值存储到Int中会造成损失

相关问题