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.

3
  • possible duplicate of 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). Commented Dec 25, 2011 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? Commented Dec 25, 2011 at 22:24
  • @birryree No whitespace in condition or action, and no parentheses Commented Dec 25, 2011 at 22:29

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Yes, but I also want to ignore the parentheses
Use the replace method of the String class to replace parentheses with empty strings.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.