Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression["0-9"] issue in java

I have a text file as follows:


Title
XYZ
Id name
1  abc
2  pqr
3  xyz

I need to read the content starting with the integer value and I used the regular expression as in the following code.

public static void main(String[] args) throws FileNotFoundException {
   FileInputStream file= new FileInputStream("C:\\Users\\ap\\Downloads\\sample1.txt"); 
   Scanner scanner = new Scanner(file);
          while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("[0-9]")) {
                System.out.println("Line: "+line);
            }
           }
}

The above code can't detect the lines starting with integers. However, it works fine if single integer values are passed to startsWith() function. Please suggest, where I went wrong.

like image 319
Anish Avatar asked Dec 06 '25 20:12

Anish


2 Answers

String#startsWith(String) method doesn't take regex. It takes a string literal.

To check the first character is digit or not, you can get the character at index 0 using String#charAt(int index) method. And then test that character is digit or not using Character#isDigit(char) method:

if (Character.isDigit(line.charAt(0)) {
    System.out.println(line);
}
like image 163
Rohit Jain Avatar answered Dec 08 '25 10:12

Rohit Jain


For regex you can use the "matches" method, like this:

line.matches("^[0-9].*")
like image 21
Fabio Avatar answered Dec 08 '25 09:12

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!