aug70co
aug70co

Reputation: 3987

Java regex question with groups

I want to be able to parse below strings with a single regex using groups? There may or may not be single/multiple whitespace between dash and numbers.

Input string examples:

"0.4 - 1.2 Mathematics"
"0.7-1.3 Physics"
"0.3-    0.7      Chemistry"
"4.5 Biology"
"2 Calculus"

group(1) -> lowGrade -> Float
group(2) -> highGrade -> Float (if exists)
group(3) -> class -> String

Can you help with the regex? Thanks

Upvotes: 0

Views: 3585

Answers (3)

stema
stema

Reputation: 92976

So here is your working solution, if the "highGrade" is not available the second group is NULL.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
    public static void main(String[] args)
    {
        String Text = "0.4 - 1.2 Mathematics";
        Pattern p = Pattern.compile("^" + // Match the start of the string
                "(\\d+(?:\\.\\d+)?)" + // Match the first float, the fraction is optional, (?:) is a non capturing group
                "(?:\\s*-\\s*" + // Match the whitespace and the - . This part including the following float is optional
                "(\\d+(?:\\.\\d+)?))?" + // Match the second float, because of the ? at the end this part is optional
            "\\s*(.*)" + // Match the whitespace after the numbers and put the rest of the chars in the last capturing group
            "$"); // Match the end of the string

        Matcher m = p.matcher(Text);

        if (m.matches()) {
            System.out.println(m.group(1));
            System.out.println(m.group(2));
            System.out.println(m.group(3));
        }
    }
}

Upvotes: 2

Erick Martinez
Erick Martinez

Reputation: 825

Have you tried this:

String s = "Mathematics 0.4 - 1.2";
pattern = Pattern.compile("([^\d\.\s]+)\b\s+(\d+\.\d+)\D*(\d+\.\d+)?");
matcher = pattern.matcher(s);
if (matcher.matches()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
}

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93020

String s = "Mathematics 0.4 - 1.2";

Matcher m = Pattern.compile("(.*?) *([0-9.]+) *(- *([0-9.]*))?").matcher(s);
if(m.matches()){
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(4));
}

Upvotes: 1

Related Questions