问题描述
我正在编写一个程序来确定字符串是否是递归的回文。我决定尝试使用正则表达式,但我在理解语法方面遇到了一些麻烦。我需要做的是比较第一个和最后一个字符,看它们是否相同。我怎么能这样做?
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?
谢谢!
编辑:我觉得这很有用:
I found this helpful: AirSource Ltd's answer to Degvik's question
推荐答案
是的,如果第一个和最后一个字符相同,您可以确定使用正则表达式:
Yes, you can determine using regex if the first and last characters are the same:
str.matches("(.).*\\1")
这使用反向引用来表示第1组,它捕获第一个字符。
This uses a "back reference" to refer to "group 1", which captures the first character.
示例:
"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)));
}
这篇关于java正则表达式找到第一个和最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!