2

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.

user1754738
  • 347
  • 5
  • 13

2 Answers2

2

This is a one-liner:

String part = str.replaceAll(".*:(.*)].*", "$1");

The regex captures the whole input, which is replaced with the 1st group, which captures the part you want, effectively return just the part you want.

Here's some test code:

public static void main(String[] args) {
    String str = "Lorem ipsum dolor [cookie:firstname] adipiscing elit.";
    String part = str.replaceAll(".*:(.*)].*", "$1");
    System.out.println(part);
}

Output:

firstname
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • You might want to add a leading `\\[` to the pattern, so that it only grabs the substring enclosed within brackets. – David R Tribble Oct 17 '12 at 23:36
  • This worked but for some reason it caused the componet which held the text to reload. Thanks, will be useful in my future exercises – user1754738 Oct 18 '12 at 15:29
1

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
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525