mike_hornbeck
mike_hornbeck

Reputation: 1622

How to match letter combination and it's occurences

Let's say I have this text :

antianti
barbary
barberbarber

How can I match other occurences of the first 2 letters in each of those 'words', for example an\an in the first word and ba\ba in the second one ? I was trying to get it with :

/(^\w{2})/gm

Plus \n or {2} but to no eval. Any tips what am I doing wrong here ?

Upvotes: 2

Views: 67

Answers (3)

anubhava
anubhava

Reputation: 784998

Probably this regex should work out for you:

^(\w{2})(?=.*\1)

Online Demo: http://regex101.com/r/jV7uF3

Upvotes: 1

SethB
SethB

Reputation: 2090

This captures the first two characters of each line and the last occurrence.

/^(\w{2})(?:.*)(\1)/gm

This captures the first two characters of each line and the next occurrence.

/^(\w{2})(?:.*)(\1)/gmU

Now this gets ugly, but ... the next two occurrences.

/^(\w{2})(?:.*(\1).*(\1)|.*(\1))/gmU

Upvotes: 1

Barmar
Barmar

Reputation: 780798

Capture the first two letters in a lookbehind, and then use back-references to match later occurrences.

/^(?<=(\w\w).*)\1/gm

Upvotes: 0

Related Questions