From 894f76d8bc032483cd9043de5751c8e74d770a78 Mon Sep 17 00:00:00 2001 From: Reinhard Pointner Date: Tue, 22 Nov 2016 09:59:42 +0800 Subject: [PATCH] Replace numbers 1..12 with Roman numerals e.g. "Star Wars: Episode 4" -> "Star Wars: Episode IV" --- .../format/ExpressionFormatMethods.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/source/net/filebot/format/ExpressionFormatMethods.java b/source/net/filebot/format/ExpressionFormatMethods.java index acc82807..908f895f 100644 --- a/source/net/filebot/format/ExpressionFormatMethods.java +++ b/source/net/filebot/format/ExpressionFormatMethods.java @@ -21,6 +21,7 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; +import java.util.TreeMap; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -329,6 +330,36 @@ public class ExpressionFormatMethods { return self; } + /** + * Replace numbers 1..12 with Roman numerals + * + * e.g. "Star Wars: Episode 4" -> "Star Wars: Episode IV" + */ + public static String roman(String self) { + TreeMap numerals = new TreeMap(); + numerals.put(10, "X"); + numerals.put(9, "IX"); + numerals.put(5, "V"); + numerals.put(4, "IV"); + numerals.put(1, "Ⅰ"); + + StringBuffer s = new StringBuffer(); + Matcher m = compile("\\b\\d+\\b").matcher(self); + while (m.find()) { + int n = Integer.parseInt(m.group()); + m.appendReplacement(s, n >= 1 && n <= 12 ? roman(n, numerals) : m.group()); + } + return m.appendTail(s).toString(); + } + + public static String roman(Integer n, TreeMap numerals) { + int l = numerals.floorKey(n); + if (n == l) { + return numerals.get(n); + } + return numerals.get(l) + roman(n - l, numerals); + } + /** * Apply ICU transliteration *