Prash
Prash

Reputation: 554

Java String regular expression on string array to capture nested data

[
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))
]

As you can see in the above object array i want to split and retrieve all the objects starting with the name DmetaD and DConD as string .

example:

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

String y=DConD(data=abc)

Upvotes: 1

Views: 66

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You can use Pattern & Matcher with this regex (DmetaD\\(.*?\\)|DConD\\(.*?\\)) for example If you are using Java 9+ :

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

Output

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)

Before Java 9 you can use :

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

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

Details about the regex (DmetaD\(.*?\)|DConD\(.*?\))

  • DmetaD\(.*?\) a matches which start with DmetaD followed by any thing between parenthesis.
  • | or
  • DConD\(.*?\) a matches which start with DConD followed by any thing between parenthesis.

Upvotes: 1

Related Questions