I have an ArrayList<String>
which I iterate through to find the correct index given a String. Basically, given a String, the program should search through the list and find the index where the whole word matches. For example:
ArrayList<String> foo = new ArrayList<String>();
foo.add("AAAB_11232016.txt");
foo.add("BBB_12252016.txt");
foo.add("AAA_09212017.txt");
So if I give the String AAA
, I should get back index 2
(the last one). So I can't use the contains()
method as that would give me back index 0
.
I tried with this code:
String str = "AAA";
String pattern = "\\b" + str + "\\b";
Pattern p = Pattern.compile(pattern);
for(int i = 0; i < foo.size(); i++) {
// Check each entry of list to find the correct value
Matcher match = p.matcher(foo.get(i));
if(match.find() == true) {
return i;
}
}
Unfortunately, this code never reaches the if
statement inside the loop. I'm not sure what I'm doing wrong.
Note: This should also work if I searched for AAA_0921
, the full name AAA_09212017.txt
, or any part of the String that is unique to it.
_
is considered a word character..so it wont act as word boundary..return i;
?