Reputation: 842
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
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