I'm currently brushing up on my coding skills and working through some easy problems I've found online. The particular task is to input a txt file that contains any number of lines, and to have the program check each line and return "True" or "False" depending on whether that line contains all 26 letters of the alphabet. I feel like I'm almost finished, but my regular expression to match the string to [a-z] returns false no matter what I do. I've tried changing the string to lowercase, removing spaces, and nothing seems to work.
Here's a link to the project as well.
The text I have in my text file currently is "The quick brown fox jumps over the lazy dog."
package easy139;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class easy139 {
public static void main(String[] args) {
try {
Scanner in = new Scanner(new FileReader("input.txt"));
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
String noSpaces = line.replaceAll(" ","");
if (noSpaces.matches("[a-z]")) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
in.close();
} catch (IOException e) {
}
}
}
Your test is returning false because the regex [a-z]
means "exactly one letter".
A regex that works with String.matches()
is:
(?i)(?=.*a)(?=.*b)(?=.*c)...(?=.*z).*
This uses one look ahead for each letter, each of which asserts that the letter is present. The (?i)
switch turns on case insensitivity.