2013-05-27 30 views
-7

考虑下面的例子中,提取字符串中的Java

String str = "Record of student " + 
       "Name: Aasim ; Surname: Khan; Age: 15 ; Weight: 60; " + 
       "School : Abcd High School This is record of Student"; 

我想在其中包含埃西姆,汗,60,ABCD高中

+2

然后写一些Java来解压。当你有一个特定的问题,那么你应该问问题,当然,你[做你的研究](http://stackoverflow.com/faq) – SomeShinyObject

回答

0

首先,拆分您串串的提取物阵列通过分号获得每个键值对。然后用冒号分割每个部分。

4

你可以做这样的事情:

for (String retval: str.split(";")){ 
      String[] parts = retval.split(":"); 
      String neededPart = parts[1]; 
      // do your stuff with your neededPart 
    } 
0

首先尝试Colan之间获得的数据(:)和semicolan(;)的retrived数据添加到字符串数组。尝试打印它。使用StringTokenizer类获取colan和semicolan之间的数据。

0

理想情况下,你想用正则表达式来做到这一点:

为了简化考虑:String str = "Record of student " + "Name: Aasim ; Surname: Khan;

import java.util.Pattern.*; 
Pattern p = Pattern.compile("Record of student Name:(.*) ; Surname:(.*).*") 
Matcher m = p.matcher(str) 
if(m.matches()){ 
    String name = m.group(1); 
    //so on 
} 
+0

真:)。但要开始使用它可能有助于了解哪个组与哪个字符串相关联。 – Jatin

0

您可以使用正则表达式。我们的想法是:;字符之间的链(\w是在正则表达式的字母数字字符)相匹配,如下面的示例代码:

Pattern p = Pattern.compile(".* : (\\w+) ; .*"); 
Matcher m = p.matcher(str); 
if(m.matches()) { 
    System.out.println("The first substring is: " + m.group(1)); 
} 

然后所有的子字符串将在m,如你所见在这个例子中。

0

您可以使用StringTokenizer类,如下为例:

String str = "Record of student Name: Aasim ; Surname: Khan; Age: 15 ; Weight: 60; School : Abcd High School This is record of Student"; 

    ArrayList<String> tokens1=new ArrayList<>(); 
    ArrayList<String> tokens2=new ArrayList<>(); 


    StringTokenizer s1=new StringTokenizer(str, ";"); 
    while (s1.hasMoreElements()) { 
     tokens1.add((String) s1.nextElement()); 
    } 

    for (String string : tokens1) { 
     System.out.println(string); 
     StringTokenizer s2=new StringTokenizer(string, ":"); 

     int i=0; 
     while (s2.hasMoreElements()) { 
      s2.nextElement(); 
      tokens2.add((String) s2.nextElement()); 
     } 
    } 
    for (String string : tokens2) { 

     System.out.println(string); 
    }