简体   繁体   中英

java regex find first and last characters

I'm writing a program that determines if a string is a palindrome recursively. I've decided to try and use regex, but I'm having a bit of trouble understanding the syntax. What I need to do is compare the first and last char to see if they are identical. How can I go about doing this?

Thanks!

EDIT: I found this helpful: AirSource Ltd's answer to Degvik's question

There's really no need to use regular expressions if you want to work recursively here, and no need to use them if you want to test for palindromes in general (if it's even possible). You can try something like this:

public static boolean isPalindrome(String s) {
    if (s.length() < 2) return true;
    return s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1, s.length() - 1));
}

Yes, you can determine using regex if the first and last characters are the same:

str.matches("(.).*\\1")

This uses a "back reference" to refer to "group 1", which captures the first character.

Example:

"aba".matches("(.).*\\1") // true
"abc".matches("(.).*\\1") // false

You could then recursively remove the first and last characters and check again:

public static boolean isPalindrome(String str) {
    return str.length() < 2 || 
        (str.matches("(.).*\\1") && isPalindrome(str.substring(1, str.length() - 1)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM