regex match two sets of digits from line

Viewed 46

Matching two sets of numbers from a line. (2.66 and 34.3). These can digits are variable in length but surrounded by whitespace. eg Ox 2.66 abcda 34.3 abfdasd

I got 2.66 with \b(?:Ox)\s+(\d*\.*?\d+)

Any resources that can guide me in the right direction? Im stuck on matching the second separately. cheers

2 Answers

You could write the following regular expression: ([\d\D\s]*). If you want numeric values only then ([\d\.]*).

You may continue the regex pattern and capture the second number after another word:

\bOx\s+(\d*\.?\d+)\s+\S+\s+(\d*\.?\d+)

See the regex demo. The second number will be in Group 2.

Details:

  • \b - a word boundary
  • Ox - a word Ox
  • \s+ - one or more whitespaces
  • (\d*\.?\d+) - Group 1: zero or more digits, an optional ., one or more digits
  • \s+ - one or more whitespaces
  • \S+ - one or more non-whitespaces
  • \s+ - one or more whitespaces
  • (\d*\.?\d+) - Group 2: zero or more digits, an optional ., one or more digits.

See a Java demo:

import java.util.*;
import java.util.regex.*;
 
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "Ox   2.66 abcda   34.3 abfdasd";
        Pattern pattern = Pattern.compile("\\bOx\\s+(\\d*\\.?\\d+)\\s+\\S+\\s+(\\d*\\.?\\d+)");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()){
            System.out.println(matcher.group(1)); // => 2.66
            System.out.println(matcher.group(2)); // => 34.3
        } 
    }
}
Related