如何使用Java标准API从字符串派生特定数据?

时间:2010-10-18 13:08:23

标签: java

假设

str = ABCorp(sap234) #$% rain-drop(docman8) 093 (jac3k(turtle))

现在我如何从上面的字符串中得到以下内容:

String[] one = {"ABCorp", "rain-drop", "jac3k"}; 
String[] two = {"sap234","docman8","turtle"};

对此有什么想法吗?

3 个答案:

答案 0 :(得分:2)

我认为str = ABCorp(sap234) #$% rain-drop(docman8) 093 (jac3k(turtle))是整个字符串, 使用PatternMatcher

答案 1 :(得分:1)

利用Regular Expressions!

的强大力量

答案 2 :(得分:1)

这应该这样做:

import java.util.*;
import java.util.regex.*;

public class Main {
    public static void main(String[] args) {

        String str = "ABCorp(sap234) #$% rain-drop(docman8) 093 (jac3k(turtle))";

        ArrayList<String> arr1 = new ArrayList<String>();
        ArrayList<String> arr2 = new ArrayList<String>();

        String s = "\\b(\\p{Graph}+)\\(([^)]+)\\)";
        Pattern p = Pattern.compile("("+s+")|(\\("+s+"\\))");
        Matcher m = p.matcher(str);

        while (m.find()) {
            arr1.add(m.group(m.group(1) == null ? 5 : 2));
            arr2.add(m.group(m.group(1) == null ? 6 : 3));
        }

        String[] one = arr1.toArray(new String[0]);
        String[] two = arr2.toArray(new String[0]);
        System.out.println(Arrays.toString(one));
        System.out.println(Arrays.toString(two));
    }
}

打印:

[ABCorp, rain-drop, jac3k]
[sap234, docman8, turtle]