EdXX
EdXX

Reputation: 890

Java Regular Expression for finding specific string

I have a file with a long string a I would like to split it by specific item i.e.

String line = "{{[Metadata{"this, is my first, string"}]},{[Metadata{"this, is my second, string"}]},{[Metadata{"this, is my third string"}]}}"

String[] tab = line.split("(?=\\bMetadata\\b)");

So now when I iterate my tab I will get lines starting from word: "Metadata" but I would like lines starting from:

"{[Metadata"

I've tried something like:

 String[] tab = line.split("(?=\\b{[Metadata\\b)");

but it doesnt work. Can anyone help me how to do that, plese?

Upvotes: 1

Views: 55

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Here is solution using a formal pattern matcher. We can try matching your content using the following regex:

(?<=Metadata\\{\")[^\"]+

This uses a lookbehind to check for the Metadata marker, ending with a double quote. Then, it matches any content up to the closing double quote.

String line = "{{[Metadata{\"this, is my first, string\"}]},{[Metadata{\"this, is my second, string\"}]},{[Metadata{\"this, is my third string\"}]}}";
String pattern = "(?<=Metadata\\{\")[^\"]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

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

this, is my first, string
this, is my second, string
this, is my third string

Upvotes: 0

Jan
Jan

Reputation: 43169

You may use

(?=\{\[Metadata\b)

See a demo on regex101.com.


Note that the backslashes need to be escaped in Java so that it becomes

(?=\\{\\[Metadata\\b)

Upvotes: 2

Related Questions