1

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

4 Answers 4

6

You have to define groups in your regex:

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

or

"<encoded:(\\d+),([^>]*)"
Sign up to request clarification or add additional context in comments.

3 Comments

In Java to pass \ literal it must be written as \\. So \d should be \\d. Anyway +1.
@Jatin you need to capture groups. Instead group() use group(1) and group(2).
+1 for showing two options—lazy quantifier or negated character class.
3

try

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

6 Comments

better to use replaceFirst?
It works too, but I dont think it makes any difference in this situation
if message request contained a similar innner tag, it would fail right?
tested "<encoded:2,Message > request>" s2 returns "Message > request"
Sure, in this case replaceAll won't work, we will need to use Matcher.find
|
0

Try

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

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

Comments

0

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));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.