sarghau
sarghau

Reputation: 572

Extracting text inside "[[ ]]" in java

I have a string which contains text inside parenthesis. I need to extract text present inside "[[ ]]" parenthesis using Java. Also, there are multiple occurrences of "[[ ]]" parenthesis. I would like to extract text from all of them.

For example:

    String text = "[[test]] {{test1}} [[test2]]"; 

Expected Output: test test2

Can anyone help please?

Upvotes: 0

Views: 100

Answers (2)

Chthonic Project
Chthonic Project

Reputation: 8366

It's a simple regular expression match:

Pattern p = Pattern.compile("\\[\\[.*?\\]\\]");

Use a Matcher with lookingAt() method to get the result.

To remove the "[[" and "]]" after that, just add a String#replace().

Upvotes: 5

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

you can use this:

String text = "[[test]] {{test1}} [[test2]]";
Pattern p = Pattern.compile("\\[\\[(.*?)]]", Pattern.DOTALL);
Matcher m = p.matcher(text); 
while (m.find()) {
    System.out.print(m.group(1));
}

Upvotes: 2

Related Questions