2

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.

eis
  • 51,991
  • 13
  • 150
  • 199
unlimitednzt
  • 1,035
  • 2
  • 16
  • 25

1 Answers1

1

t.length()-1 is the problem. What if t is empty ""? . You need to make a null and empty check before you call t.charAt()

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Thank you for the answer, but it didn't work. I edited my post with adding the code you'd suggested, please let me know if you see the problem now. – unlimitednzt Sep 23 '14 at 14:09
  • @Ozilophile - can you give complete program?. What is `i`, what is `list`? – TheLostMind Sep 23 '14 at 14:14
  • i is a title of a product - example - Samsung Galaxy S3 Mini (GT-i8190) Factory Unlocked International Version - WHITE. list is a LinkedList of keywords (strings) - example - "plus", "with" and so on (without quotes, of course). – unlimitednzt Sep 23 '14 at 14:33