Hello,

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()) {
    System.out.println(m.group());
}

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?

Thanks!

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.

Hi,

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.