Files
kr_1/CurrencyParser.java
2026-05-23 15:11:39 +00:00

38 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import java.util.regex.*;
public class CurrencyParser {
/**
* Парсит курс USD с актуальной страницы ЦБ
* РФ[](https://cbr.ru/currency_base/daily/)
* Структура: таблица с строкой
* <tr>
* <td>840</td>
* <td>USD</td>...
* <td>76,0535</td>
* </tr>
*/
public static double parseUSD(String html) {
// Более точный и надёжный regex под текущую верстку сайта
Pattern pattern = Pattern.compile(
"<td>USD</td>\\s*" +
"<td>1</td>\\s*" +
"<td>Доллар США</td>\\s*" +
"<td>([0-9,]+)</td>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String rateStr = matcher.group(1).replace(',', '.'); // заменяем запятую на точку
try {
return Double.parseDouble(rateStr);
} catch (NumberFormatException e) {
System.err.println("Ошибка парсинга числа: " + matcher.group(1));
}
}
return -1; // не удалось найти
}
}