Question

The output is fine, I'm assuming the input is "nice" and of the form x/y, with no spaces, and is only integer values:

run:
272/273
matching group 1
272
273
matching group 2
BUILD SUCCESSFUL (total time: 0 seconds)

code:

package stackoverflow;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.out;

public class Ratio {

    private static String line = "272/273";

    public static void main(String[] args) {
        out.println(line);
        ratios(1);
        ratios(2);
    }

    private static void ratios(int numeratorDenominator) {
        out.println("matching group " + numeratorDenominator);
        Pattern pattern = Pattern.compile("(\\w+)");
        Matcher matcher;
        matcher = pattern.matcher(line);
        while (matcher.find()) {
            try {
                out.println(matcher.group(numeratorDenominator));
            } catch (IndexOutOfBoundsException obe) {
            }
        }
    }
}

However, it's not quite up to par. Is there a different, or better, way to get the denominator? I'm not looking for some obscure regex, but, for instance, to anchor to the end of the line, get the last word instead of first?

For my purposes, word works fine, although digits would also work. /d I think.

Was it helpful?

Solution

Since we're assuming that the input is nice:

String regex = "/(\\d+)$"

/ matches /
(\\d+) is a capturing group for 1 or more numbers that come after /
$ means end of string.

OTHER TIPS

Try with split()

String line = "272/273";
String num  = line.split("/")[0];
String den  = line.split("/")[1]; 

This is closer to what I was aiming for:

package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.out;

public class Ratios {

    private static String line = "272/273";
    private static String denominator, numerator;

    public static void main(String[] args) {
        out.println(line);
        denominator = ratios(1);
        numerator = ratios(2);
        out.println(denominator);
        out.println(numerator);
    }

    private static String ratios(int numeratorDenominator) {
        Pattern pattern = Pattern.compile("(\\d+)\\/(\\d+)");
        Matcher matcher;
        matcher = pattern.matcher(line);
        String result = null;
        while (matcher.find()) {
            try {
                result =matcher.group(numeratorDenominator);
            } catch (IndexOutOfBoundsException obe) {
            }
        }
        return result;
    }
}

alternatives appreciated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top