0

I have a string "Spec Files: 15 passed, 5 failed, 20 total (100% completed) in 00:08:53".

I need to use regex and print the following:

Passed: 15
Failed: 5
Total: 20

And also need to compute and print the pass percentage. Pls help.

I'm using below code:

String line = "Spec Files:     15 passed, 5 failed, 20 total (100% completed) in 00:08:53";
Pattern p = Pattern.compile("(\\d+)\\s+");
Matcher m = p.matcher(line);
while(m.find()) {
    System.out.println(m.group());
} 
azro
  • 53,056
  • 7
  • 34
  • 70
afser
  • 1
  • 1
    Your code doesn't compute anything. Show us your attempt. SO is not a write-code-for-me site. – Toto Oct 03 '19 at 17:35
  • Pattern p = Pattern.compile("(\\d+)\\s+(\\D{6})"); Matcher m = p.matcher(line); while(m.find()) { System.out.println(m.group()); } Made able change and was able to print. not sure how to calculate the pass percentage. – afser Oct 03 '19 at 17:36

1 Answers1

0

You need a regex that captures the 2 elements you need : text and value, then print them in the good order :

String line = "Spec Files:     15 passed, 5 failed, 20 total (100% completed) in 00:08:53";
Pattern p = Pattern.compile("(\\d+)\\s+(\\w+)");
Matcher m = p.matcher(line);
while (m.find()) {
    System.out.println(m.group(2) + ": " + m.group(1));
}
/*
passed: 15
failed: 5
total: 20

Pass %:

Map<String, Integer> map = new HashMap<>();
while (m.find()) {
    System.out.println(m.group(2) + ": " + m.group(1));
    map.put(m.group(2), Integer.parseInt(m.group(1)));
}
double passPercentage = map.get("passed") / (double) map.get("total");
System.out.println(passPercentage);

OR

    int passed = 0, total = 0;
    while (m.find()) {
        System.out.println(m.group(2) + ": " + m.group(1));
        if (m.group(2).equals("passed")) {
            passed += Integer.parseInt(m.group(1));
        } else if (m.group(2).equals("total")) {
            total += Integer.parseInt(m.group(1));
        }
    }
    double passPercentage = passed / (double) total;
    System.out.println(passPercentage);
azro
  • 53,056
  • 7
  • 34
  • 70
  • @arzo thanks. if i want to calculate the pass percentage by using these values, is there a function to do so? – afser Oct 03 '19 at 18:23
  • @afser you could now think about voting up/accepting the answer if it fits your question ;) – azro Oct 04 '19 at 17:53