ageoff
ageoff

Reputation: 2828

Java regex between strings multiple times on same line

I am trying to extract the values between `[::[' and ']::]'. The problem I am having is there are multiple instances of this in the same string and it is only picking up the first one. Any help with my regex? here is my code:

Sample input: line = "TEST [::[NAME]::] HERE IS SOMETHING [::[DATE]::] WITH SOME MORE [::[Last]::]";

Pattern p = Pattern.compile("\\[::\\[(.*?)\\]::\\]");
Matcher m = p.matcher(line);
if (m.find()) {
    System.out.println(m.group(1));
}

Upvotes: 1

Views: 859

Answers (1)

fge
fge

Reputation: 121710

Your regex is OK. What you need to do is cycle through the matches, a Matcher can match several times!

while (m.find())
    System.out.println(m.group(1));

A Matcher will try again from the end of the last match (unless you use \G but that's pretty special)

Upvotes: 6

Related Questions