javaregexstringtokenizer

Regex and StringTokenizer Syntax Error


I'm new to regular expressions and StringTokenizer, and I'm getting a syntax error whenever I put this regex in matches:

while ((line = br.readLine()) != null) { 
    StringTokenizer stringTokenizer = new StringTokenizer(line, "\n");

    while (stringTokenizer.hasMoreElements()) {
        String function = stringTokenizer.nextElement().toString();

        if (function.matches(\\s*(unsigned int|float|int|char|void|double)(\\s)+[a-zA-Z_](\\w)*(\\s)*\\((\\s)*((((unsigned int|float|int|char|double)(\\s)*,(\\s)*)*((unsigned int|float|int|char|double)(\\s)*))|(\\s)*|(void)(\\s)*)\\)(\\s)*\\;)) {
            System.out.println("VALID - ");
        }
    }
}

Solution

  • enclose your string withing quotes " ", And note that when using the operator "or" (|) for two consecutive words, we should use them in parenthesis ((unsigned int) | float)


    while ((line = br.readLine()) != null) { 
    StringTokenizer stringTokenizer = new StringTokenizer(line, "\n");
    
    while (stringTokenizer.hasMoreElements()) {
        String function = stringTokenizer.nextElement().toString();
    
        if (function.matches("\\s*((unsigned int)|float|int|char|void|double)(\\s)+[a-zA-Z_](\\w)*(\\s)*\\((\\s)*((((unsigned int|float|int|char|double)(\\s)*,(\\s)*)*((unsigned int|float|int|char|double)(\\s)*))|(\\s)*|(void)(\\s)*)\\)(\\s)*\\;")) {
            System.out.println("VALID - ");
        }
    }
    

    }