循环遍历java中的动态字符串

时间:2015-06-04 19:39:43

标签: java

我陷入了简单的循环..我想要一种通用的方法来循环遍历java中的这个字符串

{FetchSORDetailsResult=[{SORResData=[{CaseCount=2, MiddleName=M,    SexOffenderIdNumber=429505, DOB=19760619, SexOffenderDatabaseId=NY, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/NY/11152.JPG, FirstName=STEVEN, PhotoIdentifier=11152.JPG, IsAlias=0, LastName=LEVINE}, {CaseCount=1, MiddleName=MARK, SexOffenderIdNumber=179737, DOB=19760619, SexOffenderDatabaseId=FL, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/FL/89346.JPG, FirstName=STEVEN, PhotoIdentifier=89346.JPG, IsAlias=0, LastName=LEVINE}, {CaseCount=2, MiddleName=, SexOffenderIdNumber=429505, DOB=19760619, SexOffenderDatabaseId=NY, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/NY/11152.JPG, FirstName=STEVEN, PhotoIdentifier=11152.JPG, IsAlias=1, LastName=LEVINE}]}]}

我试过了stringutils.substringBetween,但它只获得了第一组数据。

我想从字符串中获取所有数据,如SexOffenderIdNumber,DOB,firstname,lastname。该字符串可以返回多个数据。

任何帮助申请

1 个答案:

答案 0 :(得分:1)

我认为你可以使用正则表达式来实现:

public class Test{

    public static void main(String[] args){
        String data = "{FetchSORDetailsResult=[{SORResData=[{CaseCount=2, MiddleName=M,    SexOffenderIdNumber=429505, DOB=19760619, SexOffenderDatabaseId=NY, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/NY/11152.JPG, FirstName=STEVEN, PhotoIdentifier=11152.JPG, IsAlias=0, LastName=LEVINE}, {CaseCount=1, MiddleName=MARK, SexOffenderIdNumber=179737, DOB=19760619, SexOffenderDatabaseId=FL, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/FL/89346.JPG, FirstName=STEVEN, PhotoIdentifier=89346.JPG, IsAlias=0, LastName=LEVINE}, {CaseCount=2, MiddleName=, SexOffenderIdNumber=429505, DOB=19760619, SexOffenderDatabaseId=NY, Suffix=, Image=http://secure.hallpassid.com/SORPhotos/NY/11152.JPG, FirstName=STEVEN, PhotoIdentifier=11152.JPG, IsAlias=1, LastName=LEVINE}]}]}";
        Pattern pattern = Pattern.compile("\\{[.[^\\{}]]+\\}");
        Matcher matcher = pattern.matcher(data);
        ArrayList<String> matches = new ArrayList<String>();
        while(matcher.find()){
             matches.add(data.substring(matcher.start() + 1, matcher.end() - 1));       // +1-1 to cut off {}
        }
        for(String line : matches){
            for(String fragment : line.split(","))
                System.out.println(fragment.trim());
        }
    }
}

如果stringutils.substringBetween至少工作一次,你可以在循环中使用它,在子串上,从最后一个匹配结束的点到行尾,依此类推。