我有一串混合数据,一些单词和数字。这些数字要么是整数,要么是整数的比率,要么是整数前面的百分号。我试图在程序运行期间(而不是数据库)将此信息存储在 Map 中(如果有意义的话,可能是另一种类型的对象)。撇开百分号不谈,其余数据都可以解析。我总是可以期望数据是这种带有冒号的变量的确切形式。
正确的输出(标签给出有趣的缩进):
AB: 272/272 CD: 204/529 EFGH: 105 HIJKL: 105 MN: 0 OPQ: 0%
AB 272/272
HIJKL 105
CD 204/529
MN 0
EFGH 105
OPQ 0%
-----------
AB 272/272
CD 204/529
HIJKL 105/1
MN 0/1
EFGH 105/1
OPQ 0/1
第一个打印是 with Map<String,String>
,第二个是 with Map<String,Ratio>
。如果有比我自制的比例更好的选择,我很乐意使用它。
笨拙的代码,是的,过度使用静态,只是为了易于复制/粘贴:
package regex;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.out;
class Ratio {
private int numerator;
private int denominator;
private Ratio() {
}
public Ratio(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
}
public class Ratios {
private static String line = "AB: 272/272 CD: 204/529 EFGH: 105 HIJKL: 105 MN: 0 OPQ: 0%";
private static Map<String, String> rawMapStringToString = new HashMap<>();
private static Map<String, Ratio> mapStringToRatio = new HashMap<>();
public static void main(String[] args) {
out.println(line);
populateMap();
printMap(rawMapStringToString);
out.println("-----------");
ratios();
printMap(mapStringToRatio);
}
private static void populateMap() {
Pattern pattern = Pattern.compile("(\\w+): +(\\S+)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
rawMapStringToString.put(matcher.group(1), matcher.group(2));
}
}
private static void printMap(Map<?, ?> m) {
for (Map.Entry<?, ?> e : m.entrySet()) {
String key = e.getKey().toString();
String val = e.getValue().toString();
out.println(key + "\t\t" + val);
}
}
private static void ratios() {
Pattern pattern = Pattern.compile("(\\d+)/(\\d+)");
Pattern p2 = Pattern.compile("(\\w+)");
Matcher m2;
int num, den;
Ratio ratio = null;
for (Map.Entry<String, String> e : rawMapStringToString.entrySet()) {
ratio = null;
num = 0;
den = 1;
Matcher matcher = pattern.matcher(e.getValue());
while (matcher.find()) {
num = Integer.parseInt(matcher.group(1));
den = Integer.parseInt(matcher.group(2));
ratio = new Ratio(num, den);
}
if (ratio == null) {
m2 = p2.matcher(e.getValue());
while (m2.find()) {
num = Integer.parseInt(m2.group());
den = 1;
ratio = new Ratio(num, den);
}
}
mapStringToRatio.put(e.getKey(), ratio);
}
}
}
我只是在寻找一种存储这些数据的好方法。当然,百分比可以表示为比率,x/y,只需将分母更改为 100。暂时不考虑,Map 是一个不错的选择吗?
该ratios
方法和整个正则表达式似乎很脆弱,笨拙且(对我而言)难以遵循,但我不确定如何改进代码。保持Ratio
课程几乎不变,我该如何改进ratios
填充mapStringToRatio
?