字符串数组上的 Java 字符串正则表达式以捕获嵌套数据

标签 java regex string

[
Dobj(id=null, dmetaD=DmetaD(id=2068, embedded=true, size=123, comment=raghu, name=string, type=pdf)),dcont=DConD(data=abc)),
Dobj(id=null, dmetaD=DmetaD(id=2069, embedded=true, size=123, comment=raghu, name=string, type=pdf)),dcont=DConD(data=abc))
]

正如您在上面的对象数组中看到的,我想拆分并检索以名称 DmetaDDConD 开头的所有对象作为字符串。

示例:

String x=DmetaD(id=2068, embedded=true, size=123, comment=raghu, name=string, type=pdf))

String y=DConD(data=abc)

最佳答案

您可以使用Pattern & Matcher使用这个正则表达式(DmetaD\\(.*?\\)|DConD\\(.*?\\))例如,如果您使用的是 Java 9+:

String input = "...";
String regex = "(DmetaD\\(.*?\\)|DConD\\(.*?\\))";
List<String> result = Pattern.compile(regex)
        .matcher(input)
        .results()
        .map(MatchResult::group)
        .collect(Collectors.toList());

输出

DmetaD(id=2068, embedded=true, size=123, comment=raghu, name=string, type=pdf)
DConD(data=abc)
DmetaD(id=2069, embedded=true, size=123, comment=raghu, name=string, type=pdf)
DConD(data=abc)

在 Java 9 之前,您可以使用:

Matcher matcher = Pattern.compile(regex).matcher(input);

List<String> result = new ArrayList<>();
while (matcher.find()) {
    result.add(matcher.group());
}
<小时/>

有关正则表达式的详细信息(DmetaD\(.*?\)|DConD\(.*?\))

  • DmetaD\(.*?\) 匹配以 DmetaD 开头,后跟括号之间的任何内容。
  • |
  • DConD\(.*?\)DConD 开头,后跟括号之间的任何内容的匹配项。

关于字符串数组上的 Java 字符串正则表达式以捕获嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352677/

相关文章:

Java:多项选择游戏使用哪种结构

Java Try-catch block ,Catch block 不会重新提示用户输入新值

java - 将 xml 文档中出现的特殊字符(如 – 和 —)替换为相应的代码(如 等)

Javascript 正则表达式(负)lookbehind 在 firefox 中不起作用

c# - [c#]如何让控制台在一行中读取两个字符串

ios - 如何将 .cgi URL 中的参数收集到 iOS objC 中的多个字符串中?

java - IOException : Broken pipe

java - 使用多个正则表达式扫描文件

java - 如何在 Java 中取消转义 HTML 字符实体?

java - 在运行时选择实现