Jatin
Jatin

Reputation: 31724

Extract substring from string - regex

I have a String say:

<encoded:2,Message request>

Now I want to extract 2 and Message request from the line above.

private final String pString = "<encoded:[0-9]+,.*>";
    private final Pattern pattern = Pattern.compile(pString);

    private void parseAndDisplay(String line) {

        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            while(matcher.find()) {
                String s = matcher.group();
                System.out.println("=====>"+s);

            }
        }
    }

This doesn't retrieve it. What is wrong with it

Upvotes: 1

Views: 3202

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try

    String s = "<encoded:2,Message request>";
    String s1 = s.replaceAll("<encoded:(\\d+?),.*", "$1");
    String s2 = s.replaceAll("<encoded:\\d+?,(.*)>", "$1");

Upvotes: 3

hsz
hsz

Reputation: 152206

You have to define groups in your regex:

"<encoded:([0-9]+),(.*?)>"

or

"<encoded:(\\d+),([^>]*)"

Upvotes: 6

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try this out :

         Matcher matcher = Pattern.compile("<encoded:(\\d+)\\,([\\w\\s]+)",Pattern.CASE_INSENSITIVE).matcher("<encoded:2,Message request>");

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

Upvotes: 0

MozenRath
MozenRath

Reputation: 10030

Try

"<encoded:([0-9]+),([^>]*)"

Also, as suggested in other comments, use group(1) and group(2)

Upvotes: 0

Related Questions