Finding palindrome using regex

前端 未结 3 1697
说谎
说谎 2021-01-12 01:13

This question comes in an attempt to understand one of the answer in : How to check that a string is a palindrome using regular expressions?

Answer

3条回答
  •  無奈伤痛
    2021-01-12 02:08

    • ^ - matches beginning of string
    • ( - starts capture group #1
    • (.) - matches any single character except a newline, save it in capture group #2
    • (?1) - recurse = replace this group with the entire regexp capture group #1
    • \2 - matches the same thing as capture group #2. This requires the first and last characters of the string to match each other
    • | - creates an alternative
    • .? - optionally matches any one character that isn't a newline - This handles the end of the recursion, by matching an empty string (when the whole string is an even length) or a single character (when it's an odd length)
    • ) - ends capture group #1
    • $ - matches end of string or before a newline at the end of the string.

    The recursion (?1) is the key. A palindrome is an empty string, a 1-character string, or a string whose first and last characters are the same and the substring between them is also a palindrome.

提交回复
热议问题