-2

我是正则表达式的新手StringTokenizer,并且每当我将此正则表达式放入时都会出现语法错误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 - ");
        }
    }
}
4

3 回答 3

0

可能是复制和粘贴错误,但可能是您缺少正则表达式周围的引号以使其成为String. 例如:

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 - ");
        }
    }
}
于 2013-01-28T16:49:29.867 回答
0

matches方法作为方法参数......因此,将String您的正则表达式括在引号“”中 ,如下所示:

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)*\\;)")
于 2013-01-28T17:07:33.757 回答
0

用引号""将您的字符串括起来,注意当使用运算符“或” (|) 来表示两个连续的单词时,我们应该在括号中使用它们((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 - ");
    }
}

}

于 2013-01-28T17:38:51.697 回答