0

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!");
        }

    
    }
    
}    
ALSG
  • 5
  • 1
  • did you print `p` to see what's inside ? Also I don't see the opening bracket that you close (in the pattern – azro May 30 '22 at 05:51
  • Try use `Pattern.compile("[a-zA-Z]{1,2}" + lastTwo);` – azro May 30 '22 at 05:52
  • I included the closing bracket because without it, I'm getting an error: Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 23 [a-zA-Z]{1,2}[C@6d03e736 – ALSG May 30 '22 at 05:54
  • can u explain why it doesnt work with the "sub" ? It works now btw. Thanks – ALSG May 30 '22 at 05:56
  • What would expect with `sub` ? Write the expectec pattern that it would build. Also see my edited answer – azro May 30 '22 at 05:58

1 Answers1

0

It seems you didn't understand what [C@37f8bb67 (part after @ varies) is and you naivly tried to "close" the bracket. What you see is the default array toString, that has no meaning in code at all


You may just padd the pattern with the 2 last char (as a string)

var p = Pattern.compile("[a-zA-Z]{1,2}" + lastTwo);
azro
  • 53,056
  • 7
  • 34
  • 70