1

Suppose I have a String NNNN.

The regex is N+N.

How to configure the matcher to let it return NNNN, NNN and NN since NNN and NN also match pattern N+N?

2
  • You could find this yourself if you searched for overlapping regex matches. Nested is a bit different category. Commented Aug 24, 2015 at 15:30
  • @stribizhev Thank you, I just don't know what's the jargon to describe my problem. Commented Aug 24, 2015 at 15:32

1 Answer 1

5

You need to enclose your pattern in a lookahead and a capture group:

(?=(N+N))

The results are in the group 1.

Since the lookahead is a zero-width assertion, characters are not consumed by the pattern and can be "reuse" for the next match (from the next position in the string).

N    N    N    N  
x______________^  # first match
     x_________^  # second match
          x____^  # third match

x____^ is the content of the capture group and x is the start position.

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

2 Comments

Nice Answer! However, would you please tell me how could I find the start and end for each group in Java?
@spacegoing: Matcher.start() and Matcher.end().

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.