3

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)*?"

1

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Might also be worth mentioning named capturing groups to avoid getting mixed up on which group is which and being able to explicitly reference a certain group.
I don't quite understand what you mean here. Can you provide a example?
you can name your capturing groups and back-reference them with those names. Although not directly answering the question put forward, I thought it was worth mentioning to avoid any confusion caused by the nested brackets. You can then do something like (?<first>ab(?<second>ba)) to have ${first} == abba and ${second} == ba

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.