Get a number with this form \ d \ s \ d \ d \ s \ d

I am trying to get a number 28

in simple form with this form integer + space + integer + integer + space + integerI tried with this regex \\s\\d\\d\\s

, but I get both numbers 11

and28

With this expression \\d\\s\\d\\d\\s\\d

I am getting this error java.lang.NumberFormatException: For input string: "4 60 1"

.

The number must not have this form letter + space + integer + integer + space.

How can I fix this?

Plain:

ZOB/Hauptbahnhof Bussteig 11 20:04 20:34 28 21:08 21:40 22:08 22:40 23:08 23:40 00:30

      

Code:

Pattern pattern = Pattern.compile("\\s\\d\\d\\s");
//Pattern pattern = Pattern.compile("\\d\\s\\d\\d\\s\\d");

Matcher m = pattern.matcher(line);
while (m.find()) {
    value = Integer.parseInt(m.group().trim());
    if (value != 10) {
        line = line.replace(m.group(), " ").replaceAll(" +", " ");
        writer.println("Min:" + value);

        // String line3 = scanner.nextLine();

        System.out.println(value
                + " has been found in this text document " + newName);
    }

}

      

+3


source to share


2 answers


You need to use images.

Pattern pattern = Pattern.compile("(?<=\\d\\s)\\d{2}(?=\\s\\d)");

      

This will not require any trimming for whitespace.



DEMO

  • (?<=\\d\\s)

    A positive lookbehind that states that the match must be preceded by a digit and a space.

  • \d{2}

    Exactly two digits.

  • (?=\\s\\d)

    Asserts that matching digits must be followed by a space and a digit.

+4


source


Your problem is not with the pattern you are trying to match. This matches 4 60 1

as you pointed out. The problem is that you are trying to parse the whole match with Integer.parseInt()

- and obviously this is an invalid Integer.

Assuming you end up with a number 4601

, you need to sanitize the input (remove spaces) before you can parse it:



value = Integer.parseInt(m.group().trim().replaceAll("\\s", ""));

      

Edit: On second reading, your template doesn't seem to provide the output you want, so this answer doesn't solve your actual problem.

0


source







All Articles