Search code examples
javaregexuser-input

How to match a pattern with String variable in Java


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

    
    }
    
}    

Solution

  • 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);