I just started using Java regular expressions at work, and am having trouble with using the Matcher find() method.
In the following code, i is a String parameter received from the client, and 'list' is a ready made linked list with String values, and I want to find the value in the list that appears in i at the smallest possible index out of all the other list values (if there is indeed a match). The values in the list might have an asterisk at their end, which means they have a wildcard, so there are 0 or more 'word characters' in their end - so I have to consider that when searching in i. Here is the code:
Pattern checkRegex;
int tStart = i.length();
for (String t : list){
if (t.charAt(t.length()-1) == '*')
checkRegex = Pattern.compile("\\W" + t + "[0-9A-Za-z]*\\W");
else
checkRegex = Pattern.compile("\\W" + t + "\\W");
Matcher regexMatcher = checkRegex.matcher(i);
if (regexMatcher.find()){
if (tStart > i.indexOf(regexMatcher.regionStart()))
tStart = i.indexOf(regexMatcher.regionStart());
}
I get the error - Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
After debugging, I found that the program crashes at the regexMatcher.find() command - but since it is a boolean method, I don't understand what String indexes have to do here.
Appreciate your help.