简体   繁体   English

java正则表达式查找第一个和最后一个字符

[英]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编辑:我发现这很有帮助: AirSource Ltd 对 Degvik 问题的回答

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.这使用“反向引用”来引用“组 1”,它捕获第一个字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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