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.
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);
}
For regex you can use the "matches" method, like this:
line.matches("^[0-9].*")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With