Regex to get positive number

Viewed 131

I have a string that contains a number in between and I want to get all the numbers from that string for that I have this regex ( \d+ ) but it's not serving the purpose.

enter image description here

I also want to include those that are mentioned in red square, what changed do I need to make in the regex.

Edit: Relevant code

String regex = "( \\d+ )";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(textView.getText());

        while (m.find()) {
            String number = m.group().replace(" ", "");
            WAAFILogger.d("Number-regex", ":"+number+":");
            int startIndex = messageText.indexOf(number);
            int endIndex = startIndex + number.length() - 1;

            builder.setSpan(message.getSpannableListenerForNumber(number),
                    startIndex,
                    endIndex + 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            textView.setMovementMethod(LinkMovementMethod.getInstance());

        }
1 Answers

You may use either of the two:

\+?\b\d+(?!\S)
\+?(?<!\d|\d\.)\d+(?!\.?\d)

See regex demo #1 and regex demo #2. Details:

  • \+? - an optional + sign
  • \b - word boundary
  • (?<!\d|\d\.) - a negative lookbehind that fails the match if there is a digit or digit + . immediately to the left of the current location
  • \d+ - 1+ digits
  • (?!\S) - a negative lookahead that fails the match if there is no non-whitespace char immediately to the right of the current location
  • (?!\.?\d) - a negative lookahead that fails the match if there is an optional . and a digit immediately to the right of the current location.
Related