jakeinmn
jakeinmn

Reputation: 167

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

Upvotes: 1

Views: 976

Answers (5)

vandale
vandale

Reputation: 3650

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

Upvotes: 0

DaoWen
DaoWen

Reputation: 33019

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(") ("));

Upvotes: 1

cosjav
cosjav

Reputation: 2115

You can use this regular expression to remove spaces surrounding parenthesis:

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

Upvotes: 0

gmansoor
gmansoor

Reputation: 509

Try this. It replaces the string.

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

Upvotes: 0

Masudul
Masudul

Reputation: 21961

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"); 

Upvotes: 0

Related Questions