mlee_jordan
mlee_jordan

Reputation: 842

Extracting multiple groups out of a string?

I am trying to extract some information from a string as given below:

[Recently, ,, many, brane, inflation, scenarios, were, proposed, -LRB-, see, ,, e.g., ,, -LSB-, 3, -RSB-, for, a, review, -RRB-, ,, together, with, their, embeddings, into, the, -LRB-, warped, -RRB-, compactified, superstring, models, ,, in, a, good, package, with, the, phenomenological, constraints, coming, from, particle, physics, -LRB-, see, ,, e.g., ,, -LSB-, 4, -RSB-, -RRB-, .]

So what I need to extract is the values appearing between square braces (e.g. -LSB-, 3, -RSB-, && -LSB-, 4, -RSB-,)

Here is the related snippet of my code:

String pttrn = ".*-LSB-,\\s(\\d),\\s-RSB-,.*"; 
Pattern pattern = Pattern.compile(pttrn); 
m = pattern.matcher(sentence.toString()); rgx = m.find(); 
int count = 0;
while (rgx) {
    String ref = (m.group(1));             
    count++;
    System.out.println("found: " + count + " : " + m.start() + " - " + m.end());
    statement.clearParameters();
    statement.setString(1, rs.getString("ut"));
    statement.setString(2, rs.getString("sec_title"));  
    statement.setString(3, ref);
    statement.executeUpdate(); 

     }

As a result of this code, I always get one value. When I try m.group(2) I get an error saying there is no group 2.. What might I missing?

Upvotes: 0

Views: 71

Answers (2)

Jens
Jens

Reputation: 69440

You have to call find in your while loop:

  while (m.find()) {

Upvotes: 1

Matthew Franglen
Matthew Franglen

Reputation: 4532

You have only one group within your Pattern, so a single match will only provide a single group. You need to apply the search multiple times:

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

This means your code should be:

String input = "...";
Matcher matcher = Pattern.compile("-LSB-,\\s(\\d),\\s-RSB-,").matcher(input);

while (matcher.find()) {
    System.out.println(matcher.group(1));
    // the real work should go here
}

For me this prints out:

3
4

Upvotes: 2

Related Questions