I have a string which consists of tokens enclosed in square brackets [].
I need to identify these and process the string to replace them with some other derived values.
I am unable to get list of tokens via Pattern matching. Below is my code snippet.

String str = "test [text1] text [text2]";
Pattern p = Pattern.compile("(\\[\\w+\\])");
Matcher m = p.matcher(str);
if (m.find()) {

This returns the output: [text1]

My input string can contain any combination of tokens i.e. [text] can be anywhere in the string.
Could anyone please let me know what am I missing in the pattern that I am getting only the first occurence?


Edited 2 Years Ago by nikk8a

You're only getting one occurence because you're only calling find once. If you use a while-loop instead of an if, you'll call it until it returns false, which will give you all the matches.


You are correct. I realized it pretty late, that the limitation was residing in my "if" call itself.
Pretty straight forward code otherwise.

Thanks for the reply!

This question has already been answered. Start a new discussion instead.