0

I have an assignment in which I'm supposed to detect whether or not a string is a palindrome. The program is supposed to recognize non-alphanumeric characters and ignore case (eg. "a" and "A" are the same). One of the strings is " ! " (space, !, space, space) and every time I try to set everything in the string to lower case, the "!" gets completely deleted for some reason. I've tried the following:

String string = " !  ";
string = string.replaceAll("[^a-zA-Z]+","").toLowerCase(); 
//when converted into an array, the array is empty

Is there a way to handle this case? Many thanks!

Edit: from the comments, I just figured out it says "replace anything not in the alphabet". Sorry about that. I haven't learned a lot about regexes yet, so my bad.

mudkip266
  • 19
  • 3

1 Answers1

1

every time I try to set everything in the string to lower case, the "!" gets completely deleted for some reason.

You wrote:

string = string.replaceAll("[^a-zA-Z]+","").toLowerCase();

The method String#replaceAll (documentation) replaces all characters that match the given regex expression by the given character, you use "" (empty text) for substitution, that is you delete matching characters.

The regex expression

[^a-zA-Z]+

matches every character that is not a-z (a to z) nor A-Z (A to Z). The + sign repeats the pattern, it matches for 1 to infinitely many.

In words this means you delete every non alphabetic character. That is why your string, after replacing, is empty (_ denotes space):

Before: _!__
After:

For details to the regex expression, take a look at regex101/TNfQcO. They explain the expression word by word. Here are some examples, everything in blue is matched and will be deleted by your expression:

regex101 screenshot showing some examples


For palindromes check out one of many equivalent questions like

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • I would add that the best way to ignore the case of the string is to use the String.toLowerCase() method. No need for any regex here – Stav Saad Jan 18 '18 at 17:37