String.split()处于元字符+ [英] String.split() at a meta character +
问题描述
我正在编写一个简单的程序来处理方程式的字符串输入中的方程式
然而,当我运行它时,我得到一个例外,因为我试图用+替换+ 所以我可以在空格处拆分字符串。我该如何使用
I'm making a simple program that will deal with equations from a String input of the equation When I run it, however, I get an exception because of trying to replace the " +" with a " +" so i can split the string at the spaces. How should I go about using
字符串replaceAll方法来替换这些特殊字符?下面是我的代码
the string replaceAll method to replace these special characters? Below is my code
线程main中的异常java.util.regex.PatternSyntaxException:在索引0附近悬挂元字符'+'
+
^
public static void parse(String x){
String z = "x^2+2=2x-1";
String[] lrside = z.split("=",4);
System.out.println("Left side: " + lrside[0] + " / Right Side: " + lrside[1]);
String rightside = lrside[0];
String leftside = lrside[1];
rightside.replaceAll("-", " -");
rightside.replaceAll("+", " +");
leftside.replaceAll("-", " -"); leftside.replaceAll("+", " +");
List<String> rightt = Arrays.asList(rightside.split(" "));
List<String> leftt = Arrays.asList(leftside.split(" "));
System.out.println(leftt);
System.out.println(rightt);
推荐答案
replaceAll
接受正则表达式作为其第一个参数。
replaceAll
accepts a regular expression as its first argument.
+
是一个特殊字符,表示一次或多次出现的量词。因此,它应该转义为指定文字字符 +
:
+
is a special character which denotes a quantifier meaning one or more occurrences. Therefore it should be escaped to specify the literal character +
:
rightside = rightside.replaceAll("\\+", " +");
(字符串是不可变的,所以有必要将变量赋给 replaceAll
);
(Strings are immutable so it is necessary to assign the variable to the result of replaceAll
);
另一种方法是使用字符类,删除元字符状态:
An alternative to this is to use a character class which removes the metacharacter status:
rightside = rightside.replaceAll("[+]", " +");
最简单的解决方案是使用 replace
使用非正则表达式的方法字符串
文字:
The simplest solution though would be to use the replace
method which uses non-regex String
literals:
rightside = rightside.replace("+", " +");
这篇关于String.split()处于元字符+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!