regex 如何用正则表达式做一个简单的康托尔

but5z9lq  于 2023-02-05  发布在  其他
关注(0)|答案(2)|浏览(102)

我想创建一个像cantor那样改变值的方法。

String rates = "{\"rates\":{\"CAD\":1.5563,\"HKD\":9.1212,\"ISK\":162.6,\"PHP\":57.324,\"DKK\":7.4441,\"HUF\":350.68,\"CZK\":26.083,\"AUD\":1.6442,"
                 + "\"RON\":4.8405,\"SEK\":10.363,\"IDR\":17383.99,\"INR\":88.198,\"BRL\":6.5908,\"RUB\":87.735,\"HRK\":7.5243,\"JPY\":124.53,\"THB\":37.161,"
                 + "\"CHF\":1.0744,\"SGD\":1.6131,\"PLN\":4.3979,\"BGN\":1.9558,\"TRY\":8.5925,\"CNY\":8.1483,\"NOK\":10.5913,\"NZD\":1.8045,\"ZAR\":20.2977,"
                 + "\"USD\":1.1769,\"MXN\":26.066,\"ILS\":4.0029,\"GBP\":0.89755,\"KRW\":1403.15,\"MYR\":4.9194},\"base\":\"EUR\",\"date\":\"2020-08-21\"}";

我想创建方法:

public double change(int value, String country) {

因此,如果使用以下方法:改变(100,"PLN"),它应该给我:439.79
我试着考虑使用模式,但我不知道如何把我的参数字符串在正则表达式。
我试过这样的方法:

Pattern pattern = Pattern.compile("(?<country>\"([A-Z]){3}\"):(?<rate>[0-9]+\\.[0-9]+)");
apeeds0o

apeeds0o1#

我写了一个方法:

public static double zamien(int ilosc, String waluta, String kursy) {
        double result = 0.0;

        Pattern pattern = Pattern.compile("(?<kraj>([A-Z]){3}\"):(?<kurs>[0-9]+\\.[0-9]+)");

        if(!kursy.contains(waluta)) {
            throw new IllegalArgumentException("Nie ma takiej waluty!");
        }

        int firstIndex = kursy.indexOf(waluta);
        String krajIkurs = kursy.substring(firstIndex, firstIndex + 11);
        //System.out.println(krajIkurs);

        Matcher matcher = pattern.matcher(krajIkurs);

        if (matcher.matches()) {
            double rate = Double.parseDouble(matcher.group("kurs"));
            result = ilosc * rate;
        } else {
            throw new IllegalArgumentException("zly pattern!");
        }

        return result;

    }

对我来说很好,但我能做得更好吗?

5n0oy7gb

5n0oy7gb2#

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CurrencyConverter {
    private static String rates = "{\"rates\":{\"CAD\":1.5563,\"HKD\":9.1212,\"MYR\":4.9194},\"base\":\"EUR\",\"date\":\"2020-08-21\"}";
private static JsonNode root;

static {
    try {
        root = new ObjectMapper().readTree(rates);
    } catch (Exception e) {
        throw new RuntimeException("Error while parsing rates JSON string", e);
    }
}

public static double change(int value, String country) throws Exception {
    JsonNode ratesNode = root.path("rates");
    if (!ratesNode.has(country)) {
        throw new Exception("Country not found in rates");
    }

    double rate = ratesNode.get(country).asDouble();
    return value * rate;
}

}

相关问题