Search code examples
javaarraysexceptionpattern-matchingmatcher

PatternSyntax Exception,Dangling meta character '+' near index 0


I am trying to use a Matcher for some reason, but sometimes it gives me the PatternSyntax Exception . i know in my case it means that + is a reserved character and should escape it. but my string has no such character in it at all:

        Pattern p=Pattern.compile(test,Pattern.CASE_INSENSITIVE);
        StringBuffer testing=new StringBuffer (node.getNodeValue());
        matcher=p.matcher(testing);
        if(!matcher.hitEnd())
             {
         if(matcher.find())
          {

          i++;
          }
               }

the exception is thrown at Pattern p=Pattern.compile(test,Pattern.CASE_INSENSITIVE);

the test string is just some words or characters which are not in any case a + or * etc.

here is the list of words that test will be replaced with them in a for-loop:

EDIT

I used the answer of Elliott Frisch however now a strange exception is happening:

         for(int j=0;j<index2;j++)
                  {
    test = (test != null) ? test.toLowerCase() : null;
str = (str != null) ? str.toLowerCase() : "";
if (str.contains(test)) 
{


           X[Index]= keArrayList.indexOf(test);
                Index++;
            }   

  }

             int[] X=new int[100000];

           private static final double[]  Y=new double[100000];

              for(int i=0;i<Index;i++)
             {
        felan=Y[X[i]];

             }

here although the both loop indexes are much smaller than 100000 but in first iteration I get this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

is this anything related to the if condition or what?


Solution

  • You shouldn't be using a StringBuffer (StringBuilder has been preferred since Java 1.5). Also, your Pattern isn't being reused; so compiling it seems pointless. Finally, if you just want to test if your node matches a certain number of "tests" in your loop I suggest you use something like

    String str = node.getNodeValue();
    test = (test != null) ? test.toLowerCase() : null;
    str = (str != null) ? str.toLowerCase() : "";
    if (str.contains(test)) {
        i++;
    }