Home > Software engineering >  REGEX to check data text file if last two digits is greater than 70
REGEX to check data text file if last two digits is greater than 70

Time:10-29

Introduction

Hi guys, I am new to Java programming. Forgive me if I may have ask a repeated

question. Have tried to look around for similar answers on stack but cant.

Have been stuck on this for few days.

I want to read the last two digits of a text file and validate using regex. If its greater than 70

System should print "They are speeding.";

This would be the draft of the the text file.

AB12345-60 
AB22345-60 
AB32345-80

Sample Java code:

import java.io.*;

class Main {

private final int LinesToRead = 3;

private final String REGEX = ".{2}\d{5}[-]\d{2}";

public void testFile(String fileName) {

int lineCounter = 1;

 try {

  BufferedReader br = new BufferedReader(new FileReader(fileName));

  String line = br.readLine();

   while ((line != null) && (lineCounter <= LinesToRead)) {

    if (line.matches(REGEX)) {

       System.out.println("They are not speeding");
     
       } 
     
      else {
       
      System.out.println("They are speeding");

      }

     line = br.readLine();

     lineCounter  ;

        }

      } catch (Exception ex) {
        System.out.println("Exception occurred: "   ex.toString());
   }
 }

      public static void main(String[] args) {

      Main vtf = new Main();

      vtf.testFile("Data.txt");
       } }

CodePudding user response:

I suggest just doing a string split to isolate the final speed number, and then check it via an inequality:

while ((line != null) && (lineCounter <= LinesToRead)) {
    int speed = Integer.parseInt(line.split("-")[1]);

    if (speed > 70) {
        System.out.println("They are speeding");
    }
    else {
        System.out.println("They are not speeding");
    }
    line = br.readLine();
    lineCounter  ;
}
  • Related