user1754738
user1754738

Reputation: 347

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.

Upvotes: 2

Views: 633

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213391

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

Upvotes: 1

Bohemian
Bohemian

Reputation: 425358

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

Upvotes: 2

Related Questions