0

So far I've been using ^[a-zA-Z]+( [a-zA-z]+)*$ to make sure user input Has no space in the beginning and the end and not to accept numbers or special characters and only to accept alphabetical characters.

I looked at the regex list online and in my texts I can't seem to formulate one under these conditions for a recursive palindrome program:

  • Accepts strings containing upper case or lower case characters.
  • Accepts punctuation, and single spaced blanks.

I don't think I'll need a regex for the following after validation, but if there is I'd like to know what it is.

  • After validation upper case letters must be converted to lower case.
  • The punctuation and spaces are to be ignored.
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
SelfDeceit
  • 107
  • 1
  • 2
  • 13

1 Answers1

0

If I understand you correctly, you want to create a recursive palindrome checker that employs regular expressions, in Java. I'm interested in learning Java, so I gave it a shot as my own sort of "homework problem," although it is probably yours too.

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

The output is:

A man, a plan, a canal... Panama! : true
A man, a pan, a canal... Panama! : false
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145