IanWatson
IanWatson

Reputation: 1739

Regex nested backreference

Is it possible to get a nested back reference to the below regex:

<field(.*)name="(.*)EndTime"(.*)\n((.*)\n)*?<property name="fieldClass" value="java.lang.String"/>\n</field>

Ie the "((.*)\n)*?"

Upvotes: 3

Views: 2041

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4864

Yes, this is quite possible. Just be certain to watch for which numbered group you're using. Capturing groups (and thus backreferences) are numbered according to which opening bracket comes first - so, in this case, the outer brackets would yield \1, and the inner ones would yield \2.

For example, the pattern ((.+)ab)\1\2 will match the string 1234ab1234ab1234. The first capture group will match the 4 numbers plus the ab, while the second (inner) capture group will only match the numbers. Then we repeat each one, yielding the full match.

Upvotes: 8

Related Questions