我想将日期转换为单词。例如:12/12/2012
--> 12122012
并且我已经制作了数字到单词的转换器。但现在我无法打印它。
这是我的代码:
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
。这使您可以从左到右一次“吃”一个日期,从而构建人类可读的日期输出。
关于java - 使用java将日期数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112823/