xyzzy
xyzzy

Reputation: 70

Match part of a regular expression back reference

I want to write a regular expression that will match a pattern that repeats at least twice, followed by part of the same pattern.

For example, abcabca should match, as should abcabcab, defdefdefde, etcetera.

I think I need to use back references for this. I envision something like ^(.+?){2,}\1$ but somehow matching only part of the \1 back reference.

Given the repeating pattern abc, I want to match at least 2 occurrences of abc, followed by part of the string abc.

These should match:

These shouldn't:

Is this possible? If so, how can I do it?

Upvotes: 1

Views: 1061

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 30985

If you want to fit a pattern for 3 character you can use a regex like this:

\b(.{3})\1.*?\b

Working demo

enter image description here

But if you want to have whatever pattern defined for the first characters then you could use:

\b(.+)\1.*?\b

Working demo

enter image description here

Upvotes: 2

Related Questions