2

I want to check nth occurrence of a particular pattern in a input string using Java regular expression. Can you please suggest how to do that?

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
user2883028
  • 173
  • 6
  • 19
  • Use Pattern and Matcher. Count the matches and discard all until you reach your target number. – MightyPork Nov 21 '13 at 20:44
  • He's looking for a repeating pattern, not a repeating character. – Rafael Winterhalter Nov 21 '13 at 20:52
  • What code have you tried? We won't help you if you haven't done any work on your own. – james.garriss Nov 22 '13 at 19:56
  • Not enough reputation here to reopen, but even if the question is not much detailed, I believe this question shouldn't be closed: He's specifically asking for regex. Many answers in the linked "duplicate" question doesn't apply to this question. Please think twice before hitting the "close" button. – thermz Sep 20 '16 at 09:20

2 Answers2

3

This should work:

MatchResult findNthOccurance(int n, Pattern p, CharSequence src){
    Matcher m = p.matcher(src);
    for(int i = 0; i<n; i++) m.find();
    return m;
}

Basically, it just calls find repeatedly on a Matcher obtained from the Pattern. Conveniently, a Matcher is also a MatchResult, so I can just return it straight up.

thermz
  • 2,386
  • 3
  • 20
  • 28
AJMansfield
  • 4,039
  • 3
  • 29
  • 50
2

Well, you could do the following:

(?:[abc].*+){4}([abc])

This would match 4 occurences of either a, b or c followed by anything (non-eagerly matching such that any a, b or c would not be matched by this anything), followed by a b or c in a captured group ($1).

Simply replace [abc] by the pattern you are looking for. Replace the number in curly braces by n - 1.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192