Regex : match 2nd and 3rd character

17,637

Solution 1

You'll need backreferences for the first part:

egrep '^.(.)\1'

The .{2} simply matches any two characters.

If you want the 2nd and 4th characters the same, it's the same idea as above:

egrep '^.(.).\1'

Solution 2

Use backreferences. The answer to your first question (2nd, 3rd char same) is:

egrep '^.(.)\1'

http://www.regular-expressions.info/brackets.html is a simple intro to backreferences.

Share:
17,637

Related videos on Youtube

Lucas Kauffman
Author by

Lucas Kauffman

I'm a Belgian security consultant living in Singapore, I'm here to learn and help others out. Opinions are my own. Advice provided with no warranty. Find me on http://cloud101.eu Sometimes you can have a craving only hands can satisfy!

Updated on September 18, 2022

Comments

  • Lucas Kauffman
    Lucas Kauffman over 1 year

    I was doing some exercises on regular expressions, but I can't seem to be able to crack this one :

    egrep in a file where the 2nd and 3rd character are the same.

    I tried :

    egrep  '^..{2}' /usr/share/dict/dutch
    

    However this is wrong, how should I match the 2nd and 3rd character in a regex? How would I match the 2nd and 4th character in a regex (not an exercise, but I would like to know this one as well.)?