Java正则表达式提取数据

时间:2014-08-30 13:51:41

标签: java regex

我有以下String

String s = "ddddddddddd@Type={aaaa}ddddddddddddddddd@Type={dddddddddd}"

我如何使用Java正则表达式将其解压缩为:

Type=aaaa
Type=dddddddddd

4 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Extract
{
    public static final Pattern p = Pattern.compile("(Type=)(\\{(.*?)\\})+");

    public static void main(String[] args) {
        String s = "ddddddddddd@Type={aaaa}ddddddddddddddddd@Type={dddddddddd}";
        Matcher m = p.matcher(s);

        while (m.find()) {
            // Capture group 1 = "Type="
            System.out.print(m.group(1));   
            // Capture group 3 is what's between the curly braces
            System.out.println(m.group(3)); 
        }
    }
}

这会生成以下输出:

  

Type = aaaa
  TYPE = DDDDDDDDDD

答案 1 :(得分:0)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Extract {
    public static final Pattern PATTERN = Pattern.compile("(@)(\\w+)(=\\{)(d\\s*)+(})|(@)(\\w+)(=\\{)(a\\s*)+(})");
    public static void main(String[] args) {
        String s = "ddddddddddd@Type={aaaa}ddddddddddddddddd@Type={dddddddddd}";


        Matcher matcher = PATTERN.matcher(s);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }


    }
}

答案 2 :(得分:0)

你应该自己阅读正则表达式,Java已经提供了一个文档,并且有很多工具可以测试给定字符串的正则表达式。您的问题的一种可能性可能是:

"Type=\\{((?:a|d)+)\\}"

Docs in Java

QuickREx

答案 3 :(得分:0)

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Test {
    public static void main(String[] args) {
        String str = "ddddddddddd@Type={aaaa}ddddddddddddddddd@Type={dddddddddd}";

        Pattern pattern = Pattern.compile("@Type=\\{.*?\\}");
        Matcher matcher = pattern.matcher(str);

        while(matcher.find()) {
            String match = matcher.group();
            match = "Type=" + match.substring(7, match.length() - 1);
            System.out.println(match);
        }
    }
}