使用正则表达式查找回文 [英] Finding palindrome using regex

查看:130
本文介绍了使用正则表达式查找回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是为了试图了解以下答案之一: i知道这不是严格的正则表达式

递归(?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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆