我想将日期转换为单词。例如:12/12/2012
->twelve twelve two thousand twelve
并且我已经制作了数字到单词转换器。但是现在我有问题要打印出来。
这是我的代码:
String patternString = "\\d{2}/\\d{2}/\\d{4}"; // date regex
Pattern pattern = Pattern.compile(patternString); // pattern compiling
Matcher matcher = pattern.matcher(nom); // matching with pattern with input text from user
if (matcher.find()) {
String get_data = matcher.group();
if(get_data.contains("/")){ // check either has "/" slash or not
String parts[] = get_data.split("[/]"); // split process
String get_day = parts[0]; // day will store in first array
String get_month = parts[1]; // month will store in second array
String get_year = parts[2]; // year will store in third array
String s = NumberConvert.convert(Integer.parseInt(get_day))
+ NumberConvert.convert(Integer.parseInt(get_month))
+ NumberConvert.convert(Integer.parseInt(get_year));
String replace = matcher.replaceAll(s); // replace number to words
System.out.println(replace);
}
} else {...}
输入来自用户的文本:
12/12/2012 +++ 23/11/2010
但是结果也只打印第一个模式和下一个模式,也用第一个模式的值替换。
twelve twelve two thousand twelve +++ twelve twelve two thousand twelve
请给我建议解决方案
解决问题的直接方法是使用Matcher.replaceFirst()
,而不是Matcher.replaceAll()
,因为您只希望将第一个日期模式替换为日期的书面版本。
String replace = matcher.replaceFirst(s);
如果您希望一次可以处理每个数字日期,则可以使用以下代码以从左至右的方式进行处理:
String patternString = "\\d{2}/\\d{2}/\\d{4}";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(nom);
String output = "";
while (matcher.find()) {
String get_data = matcher.group();
String parts[] = get_data.split("/");
String get_day = parts[0];
String get_month = parts[1];
String get_year = parts[2];
String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));
if (output.equals("")) {
output = s;
}
else {
output += " +++ " + s;
}
String replace = matcher.replaceFirst("");
matcher = pattern.matcher(replace);
}
每次迭代之后,上述代码都会Matcher
使用一个字符串将其重置,该字符串中先前的匹配日期已从该字符串中删除。这样一来,您就可以一次从左至右“吃”一个日期,从而在您进行操作时建立易于阅读的日期输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句