Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java regular expression to check if the first and last character of a string are same

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading