简体   繁体   中英

Java String.split error

My method successfully takes a binary expression tree and turns it into prefix, postfix, and infix notation. However, due to the accuracy of the final string, it must be exactly equal.

So before I return my output, I will run a method to quickly edit that output to remove any flaws.

(* (+ 8 4) (- 7 (/ 6 3))) ===> (*(+ 8 4)(- 7(/ 6 3)))

((8 4 +) (7 (6 3 /) -) ) =====> ((8 4 +)(7 (6 3 /)-) )

What needs to be changed, are the spacing inbetween parens. My goal was to find all cases of a string, remove them, and reinput in the string without spaces.

underlines are extra spaces (* (+ 8 4) (- 7_(/ 6 3)))

My code was supposted to be String.split(") ("); but error signs... unmatched closing ')')(???

public String antibullshiter(String out) {
    out = out.replaceFirst(") (", "X"); //edited
    String[] parts = out.split("X");
    String part1 = parts[0];
    String part2 = parts[1];
    part1 = part1 + ")";
    part2 = part2 + "(";
    out = part1 + part2;
return out;}

How do I harness the power of String.split()?

edit: thanks guys, but I realized I just had to deal with the primary method in itself

As mentioned in the other answers / comments, String.split takes a pattern string (regular expression), and that's why you're getting the unmatched parenthesis error. You can use the Pattern.quote method to get the pattern string that would match your string literal:

yourString.split(java.util.regex.Pattern.quote(") ("));

As, String is immutable. To got the changes of replaceFirst method, you need to re-assign with out . Also you need to skip the Meta Character.

  out=out.replaceFirst("\\)\\s*\\(", "X"); 

Use s.replaceAll("(?<=\\\\))\\\\s(?=\\\\()","") to remove the spaces

the error is because the string is a regex string, and parenteses must be escaped with double backslash ( "\\\\(" ) otherwise they have special meaning.

Edit: use s.replaceAll("(?<=\\\\))\\\\s+(?=\\\\()","") for multiple spaces

您可以使用此正则表达式删除括号内的空格:

out=out.replaceAll("\\\\s*([()])\\\\s*", "$1");

Try this. It replaces the string.

out.replaceFirst("\\) \\(", "X");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM