2014-11-03 127 views
1

我需要將字符串拆分爲數字序列和字符之間的部分。這樣的事情:如何分割字符串的數字和字符,只能通過字符

input: "123+34/123(23*12)/100" 

output[]:["123","+","34","/","123","(","23","*","12",")","/","100"] 

這是不是有可能,或者是否有可能通過多個字符分割字符串?否則,是否有可能通過Java中的字符串進行循環?

回答

3

您可以使用正則表達式。

String input = "123+34/123(23*12)/100"; 
Pattern pattern = Pattern.compile("\\d+|[\\+\\-\\/\\*\\(\\)]"); 
Matcher matcher = pattern.matcher(input); 
while(matcher.find()) { 
    System.out.println(matcher.group()); 
} 
+0

感謝,這工作得很好,afais。 我的Paterns是:+ - * /()[]%^我的字符串看起來像這樣:「\\ d + | [\\ + \\ - \\ * \\/\\(\\)\\ [\ \ \] \\%\\ ^]「? – 2014-11-03 22:48:32

0

使用基於lookahead assertion的正則表達式來分割輸入字符串。

String input = "123+34/123(23*12)/100"; 
System.out.println(Arrays.toString(input.split("(?<=[/)+*])\\B(?=[/)+*])|\\b"))); 

輸出:

[123, +, 34, /, 123, (, 23, *, 12,), /, 100]