使用正则表达式查找回文 [英] Finding palindrome using regex
问题描述
此问题是为了试图了解以下答案之一: i知道这不是严格的正则表达式
-
^
-匹配字符串的开头 -
(
-启动捕获组#1 -
(.)
-匹配除换行符以外的任何单个字符,将其保存在捕获组#2 中
-
(?1)
-recurse =将这个组替换为整个正则表达式捕获组#1 -
\2
-与捕获组#2匹配相同的内容.这要求字符串的第一个和最后一个字符彼此匹配 -
|
-创建替代项 -
.?
-可选地匹配不是换行符的任何一个字符-通过匹配空字符串(整个字符串为偶数长度)或单个字符(如果为奇数长度) -
)
-结束捕获组#1 -
$
-匹配字符串的末尾或字符串末尾的换行符.
递归(?1)
是关键.回文是空字符串,1个字符的字符串或开头和结尾字符相同且它们之间的子字符串也是回文的字符串.
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 given by Markus Jarderot is :
/^((.)(?1)\2|.?)$/
Can someone please explain, whats exactly happening here....i need to do similar in Perl
, but not able to understand this solution!!!
PS : I am not very good in perl so please go easy ....and also "this can't be considered a regular expression if you want to be strict" - i read this line, so i am aware that this not regex strictly
^
- 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.
这篇关于使用正则表达式查找回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!