Lv99Zubat
Lv99Zubat

Reputation: 853

How do I escape parentheses in java 7?

I'm trying to split some input from BufferedReader.readLine()

String delimiters = " ,()";
String[] s = in.readLine().split(delimiters);

This gives me a runtime error.

Things I have tried that don't work:

String delimiters = " ,\\(\\)"; 

String delimiters = " ,[()]";

String[] s = in.readLine().split(Pattern.quote("() ,"));

I tried replacing the () using .replaceAll, didn't work

I tried this:

    input = input.replaceAll(Pattern.quote("("), " "); 
    input = input.replaceAll(Pattern.quote(")"), " ");
    input = input.replaceAll(Pattern.quote(","), " ");
    String[] s = input.split(" ");

but s[] ends up with blank slots that look like this -> "" no clue why its doing that

Upvotes: 1

Views: 4759

Answers (2)

Sweeper
Sweeper

Reputation: 271905

From your comment:

but I am only input 1 line: (1,3), (6,5), (2,3), (9,1) and I need 13652391 so s[0] = 1, s[1]=3, ... but I get s[0] = "" s[1] = "" s[2] = 1

You get that because your delimiters are either " ", ",", "(" or ")" so it will split at every single delimiter, even if there is no other characters between them, in which case it will be split into an empty string.

There is an easy fix to this problem, just remove the empty elements!

List<String> list = Arrays.stream(
    "(1,3), (6,5), (2,3), (9,1)".split("[(), ]")).filter(x -> !x.isEmpty())
    .collect(Collectors.toList());

But then you get a List as the result instead of an array.

Another way to do this, is to replace "[(), ]" with "":

String result = "(1,3), (6,5), (2,3), (9,1)".replaceAll("[(), ]", "");

This will give you a string as a result. But from the comment I'm not sure whether you wanted a string or not. If you want an array, just call .split("") and it will be split into individual characters.

Upvotes: 0

abstractnature
abstractnature

Reputation: 456

Mine works, for

String delimiters = "[ \\(\\)]"

Edit:

You forgot Square brakcets which represents, "Any of the characters in the box will be used as delimiters", its a regex.

Edit:

To remove the empty elements: Idea is to replace any anagram of set of delimiters to just 1 delimiter

Like.

    // regex to match any anagram of a given set of delimiters in square brackets

    String r = "(?!.*(.).*\1)[ \\(\\)]";

    input = input.replaceAll(r, "(");

    // this will result in having double or more combinations of a single delimiter, so replace them with just one

    input = input.replaceAll("[(]+", "(");

Then you will have the input, with any single delimiter. Then use the split, it will not have any blank words.

Upvotes: 1

Related Questions