正则表达式获得x / y比率的分子和分母

时间:2013-12-18 13:25:24

标签: java regex integer-arithmetic

输出很好,我假设输入是“很好”,形式为x / y,没有空格,只有整数值:

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

代码:

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) {
            }
        }
    }
}

然而,它并不完全符合标准。获得分母是否有不同或更好的方法?我不是在寻找一些不起眼的正则表达式,但是,例如,要锚定到行的末尾,得到最后一个单词而不是第一个单词?

就我的目的而言,单词工作正常,虽然数字也可以。 / d我想。

3 个答案:

答案 0 :(得分:3)

因为我们假设输入很好:

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

/匹配/
(\\d+)/之后的一个或多个数字的捕获组 $表示字符串结束。

答案 1 :(得分:1)

尝试使用split()

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

答案 2 :(得分:0)

这更接近我的目标:

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;
    }
}

替代品赞赏。