Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangling meta character

Tags:

java

regex

I keep getting an error about dangling meta character when I use '+', '*', '(', and ')'.

I've already tried escaping those characters in the regex but I still get the error. This is what I have:

"[-\\+\\*/%\\(\\)]"

Update:

test:

String input = "+";

String vals = new WNScanner(input).getNextToken();    //**********
System.out.println("token: " + vals);
System.out.println(vals.matches("[-+*/%()]"));

from another class:

    ...

    String expression = input;
    ...

public String getNextToken() {

    String[] token = {""};

    if (expression.length() == 0)
        return "";

    token = expression.split("\\s");
    recentToken = token[0];
    expression = expression.replaceFirst(token[0], "");     //*************
    expression = expression.trim();

    return token[0];


}

* there are exceptions on these lines.

like image 632
user2430361 Avatar asked May 10 '26 18:05

user2430361


1 Answers

OK, I don't know what you want to achieve there... Especially at this line:

expression = expression.replaceFirst(token[0], "");

If your input string is "+", then your whole regex is +. And that is not legal.

You need to quote the input string in order to use it in any regex-related operation, and that includes String's .replaceFirst() and .replaceAll() (but not .replace()...).

Therefore, do:

final String re = Pattern.quote(token[0]);
expression = expression.replaceFirst(re, "");
like image 183
fge Avatar answered May 13 '26 08:05

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!