I have an ArrayList<String> , which I repeat to find the correct index given by String. In principle, given the string, the program should search the list and find the index where the whole word matches. For instance:
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 String AAA , I have to return index 2 (last). Therefore, I cannot use the contains() method, as that would give me an index of 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 inside the loop. I'm not sure what I'm doing wrong.
Note. This should also work if I looked for AAA_0921 , full name AAA_09212017.txt or any part of a string unique to it.
source share