1

The String will looks like this:

String temp = "IF (COND_ITION) (ACT_ION)";
// Only has one whitespace in either side of the parentheses

or

String temp = "   IF    (COND_ITION)        (ACT_ION)  ";
// Have more irrelevant whitespace in the String
// But no whitespace in condition or action

I hope to get a new String array which contains three elemets, ignore the parentheses:

String[] tempArray;
tempArray[0] = IF;
tempArray[1] = COND_ITION;
tempArray[2] = ACT_ION;

I tried to use String.split(regex) method but I don't know how to implement the regex.

Haoming Zhang
  • 2,672
  • 2
  • 28
  • 32
  • possible duplicate of [How do I split a string with any whitespace chars as delimiters?](http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any-whitespace-chars-as-delimiters) and then you can add in `\(` and `\)` as additional things to remove (unless those parentheses are an example). – wkl Dec 25 '11 at 22:21
  • Wait, now I'm thinking about your second example (which has irrelevant whitespace in the string). Can you give us a better example of the type of strings you want to split? Is there whitespace in the condition and action? Will the parentheses be there? – wkl Dec 25 '11 at 22:24
  • @birryree No whitespace in condition or action, and no parentheses – Haoming Zhang Dec 25 '11 at 22:29

3 Answers3

2

If your input string will always be in the format you described, it is better to parse it based on the whole pattern instead of just the delimiter, as this code does:

Pattern pattern = Pattern.compile("(.*?)[/s]\\((.*?)\\)[/s]\\((.*?)\\)");
Matcher matcher = pattern.matcher(inputString);
String tempArray[3];
if(matcher.find()) {
    tempArray[0] name = matcher.group(1);
    tempArray[1] name = matcher.group(2);
    tempArray[2] name = matcher.group(3);
}

Pattern breakdown:

(.*?)           IF
[/s]            white space
\\((.*?)\\)     (COND_ITION)
[/s]            white space
\\((.*?)\\)     (ACT_ION)
Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
0

I think you want a regular expression like "\\)? *\\(?", assuming any whitespace inside the parentheses is not to be removed. Note that this doesn't validate that the parentheses match properly. Hope this helps.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

You can use StringTokenizer to split into strings delimited by whitespace. From Java documentation:

The following is one example of the use of the tokenizer. The code:

StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
  System.out.println(st.nextToken());
} 

prints the following output:

  this
  is
  a
  test

Then write a loop to process the strings to replace the parentheses.

Kavka
  • 4,191
  • 16
  • 33