到目前为止,我一直在使用^[a-zA-Z]+( [a-zA-z]+)*$
来确保用户输入在开头和结尾没有空格,不接受数字或特殊字符,只接受字母字符。
我在网上查看了正则表达式列表,在我的文本中,我无法在这些条件下为递归回文程序制定一个:
我认为在验证后我不需要以下正则表达式,但如果有,我想知道它是什么。
答案 0 :(得分:0)
如果我理解正确,你想在Java中创建一个使用正则表达式的递归回文检查器。我对学习Java感兴趣,所以我把它作为我自己的“家庭作业问题”,但它也可能是你的。
import java.lang.*;
import java.util.*;
import java.util.regex.*;
class Main
{
public static boolean recursivePalindrome(String str)
{
// We need two patterns: one that checks the degenerate solution (a
// string with zero or one [a-z]) and one that checks that the first and
// last [a-z] characters are the same. To avoid compiling these two
// patterns at every level of recursion, we compile them once here and
// pass them down thereafter.
Pattern degeneratePalindrome = Pattern.compile("^[^a-z]*[a-z]?[^a-z]*$", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Pattern potentialPalindrome = Pattern.compile("^[^a-z]*([a-z])(.*)\\1[^a-z]*$", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
return recursivePalindrome(str, degeneratePalindrome, potentialPalindrome);
}
public static boolean recursivePalindrome(String str, Pattern d, Pattern p)
{
// Check for a degenerate palindrome.
if (d.matcher(str).find()) return true;
Matcher m = p.matcher(str);
// Check whether the first and last [a-z] characters match.
if (!m.find()) return false;
// If they do, recurse using the characters captured between.
return recursivePalindrome(m.group(2), d, p);
}
public static void main (String[] args) throws java.lang.Exception
{
String str1 = "A man, a plan, a canal... Panama!";
String str2 = "A man, a pan, a canal... Panama!";
System.out.println(str1 + " : " + Boolean.toString(recursivePalindrome(str1)));
System.out.println(str2 + " : " + Boolean.toString(recursivePalindrome(str2)));
}
}
输出结果为:
A man, a plan, a canal... Panama! : true
A man, a pan, a canal... Panama! : false