0

I need to check a string for all (case sensitive) substrings which are palindromes between 2 and 7 characters with space being the separator (i.e. "aba abbbbba daba" returns "aba" and "abbbbba" but not "daba") in Javascript. This is my code.

var regex= /\b(\S?)(\S?)(\S)\S\3?\2?\1?\b/g

It works for tests I've thrown it to work so far, except for case matching. "abbA CdDc" is throwing up a match but I can't work out why since I haven't included the i flag. I'm assuming that something in my capture groups or backreferences is telling it to ignore case, but I can't work out what or how to fix it.

  • [How to check that a string is a palindrome using regular expressions?](http://stackoverflow.com/questions/233243) – t.niese Jun 26 '16 at 10:24
  • 1
    The problem is not with case insensitivity. Your regexp matches any 4-letter word `regex.test('fsck'); //true`. – Yury Tarabanko Jun 26 '16 at 10:28
  • Why do you have question marks after `\1` etc.? Certainly you don't want those to be optional. –  Jun 26 '16 at 10:33
  • Thanks, the comments pointed me in the right direction. Fixed to the below: var regex= /\b(\S)(\S?)(\S?)(\S?)\3\2\1\b/g – James Riall Jun 26 '16 at 10:39
  • Just think of this as a valuable lesson on confirmation bias: You expected it to only work on palindromes, but you never tested it against non-palindromes 4 characters long. Testing against what it should fail on is often more important than where it should pass – TemporalWolf Jun 26 '16 at 10:43

0 Answers0