java 悬空的元字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16908806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dangling meta character
提问by user2430361
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.
*这些行有例外。
回答by fge
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 regexis +
. 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()
...).
您需要引用输入字符串才能在任何与正则表达式相关的操作中使用它,其中包括String
's.replaceFirst()
和.replaceAll()
(但不包括.replace()
...)。
Therefore, do:
因此,请执行以下操作:
final String re = Pattern.quote(token[0]);
expression = expression.replaceFirst(re, "");