2014-11-03 126 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]