2011-12-25 26 views
1

该字符串将看起来像这样:如何将字符串转换为字符串数组中的Java(忽略空格和括号)

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

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

我希望能得到一个新的String数组,包含三个要素,忽略括号:

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

我试图使用String.split(regex)方法,但我没有知道如何实现正则表达式。

+0

可能重复的[如何分割字符串与任何空白字符作为分隔符?](http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-任何-空格字符-AS-分隔符),然后你可以在'\('和'\)'作为额外的东西添加删除(除非这些括号是一个例子)。 – birryree

+0

等等,现在我想你的第二个例子(其中有不相干的空白字符串中)。你能否给我们提供一个你想要分割的字符串类型的更好的例子?条件和行动中是否有空白?括号会在那里吗? – birryree

+0

@birryree没有空格的情况和行为,并没有括号 –

回答

0

您可以使用StringTokenizer分裂成由空格分隔字符串。从Java文档:

下面是一个使用tokenizer的一个例子。的代码:

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

打印以下输出:

this 
    is 
    a 
    test 

然后写一个循环到琴弦处理到replace括号。

+0

是的,但我也想忽略括号 –

+0

使用'String'类的'replace'方法用空字符串替换括号。 – Kavka

+0

不错!这种方法运作良好! –

0

我想你想一个正则表达式像"\\)? *\\(?",假设括号内的任何空白不被删除。请注意,这不会验证括号是否正确匹配。希望这可以帮助。

2

如果你输入的字符串会永远在你描述的格式,最好是基于整个模式,而不只是分隔​​符来分析它,因为这个代码:

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

模式细分:

(.*?)   IF 
[/s]   white space 
\\((.*?)\\)  (COND_ITION) 
[/s]   white space 
\\((.*?)\\)  (ACT_ION) 
+0

Thx,你的回答也很有帮助! –

相关问题