Reputation: 1024
I am trying to match within a selection in a JTextArea and I am using Matcher.region() to define the boundary of my match:
JTextComponent t;
Pattern p = Pattern.compile("string", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher m = p.matcher(t.getText()).region(t.getSelectionStart(), t.getSelectionEnd());
m.useAnchoringBounds(false);
if(m.find()) {
System.out.println("Found match from " + m.start() + " to " + m.end());
}
else {
System.out.println("No match found");
}
The above works as expected and it will find the first match within the region - if no match is found then it doesn't find a match.
However, I am trying to loop through the matches within the region (search and replace type function) and if I specify a start position to find() that is within the region then it matches outside of the region:
int cPos = m.regionStart();
if (m.find(cPos) || m.find(m.regionStart())) {
System.out.println("Found match from " + m.start() + " to " + m.end());
cPos = m.end();
}
else {
System.out.println("No match found");
}
Is this a bug or am I breaking the region if I specify a start position - even if it is contained within the region?
Upvotes: 2
Views: 1398
Reputation: 200166
From the Javadoc:
public boolean find(int start)
Resets this matcher and then [...]
(emphasis mine)
Upvotes: 2