我正在尝试执行以下操作:创建一个类,将日期从数字格式转换为格式“EEEE,MMMM dd,yyyy”,而不会影响包含日期的字符串的其余部分。
例如,“在9/6/78,发生了一件非常酷的事情......”(每个句子可能有不止一个日期甚至不正确的日期,如“31/31/88”或“11 / && / 00“以及日期如”09/06/1988“。)应该成为”1978年9月6日星期三,发生了一件非常酷的事......“我应该忽略无效日期或日期年。请注意,与上述示例类似的句子保存在文件中;此文件中每行可能有一个或多个句子;每个日期可以显示每行不止一个;日期不详;并且可能存在单行无效日期。 (我希望这澄清了我需要做的事情。(顺便说一下,我在下面解释过,我已经知道如何使用“SimpleDateFormat”将单个有效数字日期转换为“EEEE,MMMM dd,yyyy”格式,但问题是是解析这个文件中的每一行,找到一个或多个日期,(如果日期有效,转换它),然后用新格式替换数字日期。我希望现在是明确的!)
我已经通过使用“SimpleDateFormat”解决了从简单的单个数字日期到“EEEE,MMMM dd,yyyy”格式的转换,但是我很困惑,使用正则表达式来解析字符串句子,找到日期并替换它回到新格式。请注意,我使用以下语句来解决转换(我没有列出完整的解决方案,因为它很长);
// format output EEEE, MM dd yyyy
SimpleDateFormat write = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat read = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat readYy = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat writeYyyy = new SimpleDateFormat("MM/dd/yyyy");
// dates used for a test conversion
String[] dates = {
"7/20/1969","7/4/2012",
"9/11/01", // this should be 2001 (m/d/yyyy = 8 chars, mm/dd/yy = 8 chars
"02/29/1975", "6/11/1956", "31/31/00", "7/&&/88" }
现在我一直在努力找到一个应该有效的解决方案,但由于某些原因它不起作用。见下一个代码:
String line = "We landed on the moon on 7/20/1969. 7/4/2012 is the Fourth of July.";
// I expect to see "7/20/1969" and "7/20/2012" as output but the following does not
// work:
dateRegex = "^([1-9]|0[1-9]|1[012])/([1-9]|0[1-9]|[1-2][0-9]|3[01])/(\\d\\d)|(19|20)\\d\\d$";
Pattern p = Pattern.compile(dateRegex);
Matcher m = p.matcher(line);
System.out.println(line);
while(m.find()) {
System.out.println("Found " + p + " at: " + m.start());
// return the sequences characters matching "dateRegex (or so it should...?)
System.out.println("Match : " + m.group()) // it does not print 'cause nothing is found
}
// the above code works find with a simpler regex string variable, but nothing like this
// what's worng here? Is this a wrong "dateRegex" pattern? Thanks.
我很感激任何已证实结果的帮助。感谢。
答案 0 :(得分:0)
使用String.Format()?
String.format("On %s, a really cool thing happened.", DateTimeFormatter.print()DateTime.now());
当然这个例子使用了更优越的Joda Time库。你也应该这样。
<强>更新强> 在正确理解了这个问题之后(我认为)这个小例子,使用标准的Java库可以让你开始。
package com.company;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String example = "On 9/6/78, a really cool thing happened...";
SimpleDateFormat replacement = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
Pattern datePattern = Pattern.compile("\\b\\w{1,2}/\\w{1,2}/(?:\\w{4}|\\w{2})\\b");
Date now = new Date();
System.out.println(datePattern.matcher(example).replaceAll(replacement.format(now)));
}
}