I have a code that is supposed to get an input, get the last 2 letters from the first input, then match the second input with the last two letters (ex. glam, slam). The issue is that it keeps going to the else statement rather than the if statement. Is there an issue with how the pattern is constructed?
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
public class MatchyPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first word: ");
String fw;
fw = s.nextLine();
String lastTwo = fw.substring(fw.length() - 2);
char[] sub = lastTwo.toCharArray();
var p = Pattern.compile("[a-zA-Z]{1,2}" + sub + "]");
System.out.print("Enter the second word: ");
String sw;
sw = s.nextLine();
Matcher m = p.matcher(sw);
if (m.matches()){
System.out.println(fw + " rhymes with " + sw);
}else{
System.out.println("I'm not sure! Sorry!");
}
}
}