Search code examples
javaregexpalindrome

What does this regex syntax actually mean in Java?


I wrote a program to detect palindromes. It works with what I have, but I stumbled upon another bit of syntax, and I would like to know what it means exactly?

This is the line of code I'm using:

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

I understand that the replaceAll code snippet means to "match characters ([...]) that are not (^) in the range a-z and A-Z (a-zA-Z)."

However, this worked as well:

    replaceAll("[^(\p{L}')]", "");

I just don't understand how to translate that into English. I am completely new to regular expressions, and I find them quite fascinating. Thanks to anyone who can tell me what it means.


Solution

  • You should check this website: https://regex101.com

    It helped me a lot when I was writing/testing/debugging some regexes ;)

    It gives the following explanation:

    [^(\p{L}')] match a single character not present in the list below:

    • ( the literal character (
    • \p{L} matches any kind of letter from any language
    • ') a single character in the list ') literally