4

I need to match a group at the start of a string with the reverse of group at the end.
Ex:
batmantab would match because bat and tab.
racecar would match because rac and car.

current regex:

'^(\w{3})\w*\1$'

Any Suggestions?

Jotne
  • 40,548
  • 12
  • 51
  • 55
Jim Thome
  • 61
  • 1
  • 2

1 Answers1

3

You need to capture each character separately.

^(\w)(\w)(\w)\w*\3\2\1$

DEMO

But it's impossible to reverse a group which contains two or more characters through regex.

$ grep -oP '^(\w)(\w)(\w)\w*\3\2\1$' file2
batmantab
racecar
$ grep -o '^\(\w\)\(\w\)\(\w\)\w*\3\2\1$' file2
batmantab
racecar
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274