2

I have a String

String testString = "IN NEWYORK AND (OUT FLORIDA)" ; 

I want to split out this string in array Like :

String testArray[] = testString.split("\\s()");

I would like the result to be:

testArray[0] = "IN";
testArray[1] = "NEWYORK";
testArray[2] = "AND";
testArray[3] = "(";
testArray[4] = "OUT";
testArray[5] = "FLORIDA";
testArray[6] = ")";

However, the output I get is:

testArray[0] = "IN";
testArray[1] = "NEWYORK";
testArray[2] = "AND";
testArray[3] = "(OUT";
testArray[4] = "FLORIDA)";

It is splitting on white spaces but not on "(" and ")" , I want "(" and ")" to be as seperate strings .

Jesper
  • 202,709
  • 46
  • 318
  • 350
Satish Sharma
  • 3,284
  • 9
  • 38
  • 51

4 Answers4

3

Try the below:

String testArray[] = testString.split("\\s|(?<=\\()|(?=\\))");
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

split() requires a deleimeter to remove. Use StringTokenizer and instruct it to keep the delimiters.

    StringTokenizer st = new StringTokenizer("IN NEWYORK AND (OUT FLORIDA)", " ()", true);
    while (st.hasMoreTokens()) {
        String t = st.nextToken();
        if (!t.trim().equals("")) {
            System.out.println(t);
        }
    }
0
String test = "IN NEWYORK AND (OUT FLORIDA)";
// this can for sure be done better, hope you get the idea
String a = test.replaceAll("(", "( ");
String b = a.replaceAll(")", " )";

String array[] = b.split("\\s");
acerisara
  • 121
  • 5
0

If you want to do it with string split, then monstrous regexes like \s+|((?<=\()|(?=\())|((?<=\))|(?=\))) are pretty much inevitable. This regex is based on this question, btw, and it almost works.

Easiest way is to either surround parentheses with spaces as suggested by @acerisara or use StringTokenizer as suggested by @user1030723

Community
  • 1
  • 1
Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68