I’m trying to to check if the first and last characters of a string are the same. The very basic approach is to simply compare the first and last characters and it’s done.
str.charAt(0) == str.charAt(str.length()-1)?true:false;
str = "ababa"; //shall return true.
str = "abab"; //shall return false.
But is there a way to compare the whole string using pattern matcher with a pre defined regex expression?
>Solution :
Using String#matches with a backreference:
List<String> inputs = Arrays.asList(new String[] { "ababa", "abab" });
for (String input : inputs) {
if (input.matches("(.).*\\1")) {
System.out.println("MATCH: " + input);
}
else {
System.out.println("NO MATCH: " + input);
}
}
This prints:
MATCH: ababa
NO MATCH: abab