Q:

Capturing Part of String

I want to capture part of a string and I know it involves some combination of substring, regex and matches, I'm having a really hard time putting together a decent solution.  Let's say I have a paragraph of text:
String str = "Lorem ipsum dolor [cookie:firstname] adipiscing elit.";

I would like to capture the text in-between the the : and ] above, "firstname" in this case (the cookie name could be variable length).  One way I suppose is using split:
str = str.split("\\cookie:")[1]");

then perhaps a str.replace to remove the training "]" - but I'm hoping there's a more elegant way of doing this.  I'm very new to regex, but haven't be successful getting what i need down.
Thanks in advance for any assistance.

A:

You can try below regex code: -
    String str = "Lorem ipsum dolor [cookie:firstname] adipiscing elit.";
    Pattern pattern = Pattern.compile(".*?\\[.*?:(.*?)\\].*");
    Matcher matcher = pattern.matcher(str);

    if (matcher.find()){
        System.out.println(matcher.group(1));
    }

OUTPUT: -
firstname

