使用特定单词java将字符串拆分为单词数组

时间:2014-06-22 07:35:30

标签: java string split

我想拆分此String以提供我想要的输出

sinXcos(b+c)

输出为

sinX
cos(b+c)

我知道如何分割像

这样的字符串
200XY
使用

token = 200XY;
String[] mix_token = token.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

但是我如何在类似

的字符串上使用这样的东西
sinXcos(b+c)

或类似

的字符串
sinXcos(b+c)tan(z)

1 个答案:

答案 0 :(得分:1)

这将有效..

public static void main(String[] args) {
String text = "sinXcos(b+c)tan(z)";
String patternString1 = "(sin|cos|tan)(?![a-z])\\(?\\w(\\+\\w)?\\)?";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}
}



O/P:
sinX
cos(b+c)
tan(z)

2. Input :"sinabc(X+y)cos(b+c)tan(z)";
O/P :
cos(b+c)
tan(z)

解释:

取值

tring patternString1 = "(sin|cos|tan)(?![a-z])\\(?\\w(\\+\\w)?\\)?";
1. (sin|cos|tan) -->start with (sin or  cos or tan)
2. (?:![a-z]) --> negative lookahead. check if the next character is not in between [a to z].
3. \\(?\\w(\\+\\w)?\\)?--> an optional brace followed by an alphabet followed by a "+" and another alphabet.