0

I ping a host. In result a standard output. Below a REGEXP but it do not work correct. Where I did a mistake?

String REGEXP ="time=(\\\\d+)ms";

        Pattern pattern = Pattern.compile(REGEXP);
        Matcher matcher = pattern.matcher(result);
        if (matcher.find()) {
            result = matcher.group(1);
        }
6
  • 5
    \\d+ should be enough Commented Feb 27, 2015 at 9:35
  • 1
    problem solved. delete this post -_- Commented Feb 27, 2015 at 9:38
  • @Jonjongot - I think the OP needs to know why? :) Commented Feb 27, 2015 at 9:39
  • @TheLostMind Then somebody please add answer :p Btw Its been a while, and you are growing so fast. almost 14k! Commented Feb 27, 2015 at 9:40
  • If you try to compare a String with this Regexp, you could simply use result.matches(REGEXP) in an if-statement. No need for Pattern or Matcher that way (note: if result is not a String, I don't know what the outcome will be). Commented Feb 27, 2015 at 9:46

2 Answers 2

1

You only need \\d+ in your regex because

Matcher looks for the pattern (using which it is created) and then tries to find every occurance of the pattern in the string being matched.

  1. Use while(matcher.group(1) in case of multiple occurances.
  2. each () represents a captured group.
Sign up to request clarification or add additional context in comments.

Comments

1

You have too many backslashes. Assuming you want to get the number from a string like "time=32ms", then you need:

String REGEXP ="time=(\\d+)ms";

    Pattern pattern = Pattern.compile(REGEXP);
    Matcher matcher = pattern.matcher(result);
    if (matcher.find()) {
        result = matcher.group(1);
    }

Explanation: The search pattern you are looking for is "\d", meaning a decimal number, the "+" means 1 or more occurrences.

To get the "\" to the matcher, it needs to be escaped, and the escape character is also "\".

The brackets define the matching group that you want to pick out.

With "\\\\d+", the matcher sees this as "\\d+", which would match a backslash followed by one or more "d"s. The first backslash protects the second backslash, and the third protects the fourth.

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.