我似乎无法弄清楚这一点。我知道可以使用正则表达式,但实际上并没有创建它们的经验。我有一串像这样的日期:
( (Mon 3:23PM EDT) ( (Thu, Sep 3) ( (Thu, Sep 3) ( (Wed, Sep 2) ( (Tue, Sep 1) ( (Mon, Aug 31) ( (Fri, Aug 28) ( (Wed, Aug 26) ( (Wed, Aug 26) ( (Fri, Aug 21) ( (Mon, Aug 17) ( (Thu, Aug 13) ( (Thu, Aug 13)
当字符串中有时间戳记时,例如上面的3:23,我需要将其替换为今天的日期。我通过使用以下命令以所需的格式获取今天的日期:
Calendar cal = Calendar.getInstance();
SimpleDateFormat necessaryFormat = new SimpleDateFormat("EE, MMM dd");
String todaysDate = necessaryFormat.format(cal.getTime());
本质上,字符串应为
( (Mon, Sep 7) ( (Thu, Sep 3) ( (Thu, Sep 3) ( (Wed, Sep 2) ( (Tue, Sep 1) ( (Mon, Aug 31) ( (Fri, Aug 28) ( (Wed, Aug 26) ( (Wed, Aug 26) ( (Fri, Aug 21) ( (Mon, Aug 17) ( (Thu, Aug 13) ( (Thu, Aug 13)
到目前为止,我已经尝试使用一些类似的方法,但是它所要做的就是删除括号之间的字符串的第一部分:
String origStr = links.text().substring(0, links.text().indexOf("("))+
links.text().substring(links.text().indexOf(")")+"))".length());
最佳答案
您可以将replaceAll
与以下正则表达式一起使用:
(?i)\\([a-z]{3} \\d{1,2}:\\d{2}[pa]m [a-z]{3}\\)
正则表达式细分:
(?i)
-使模式不区分大小写\\(
-直角圆括号[a-z]{3}
-3个字母\\d{1,2}:
-一个空格,1或2位数字和一个:
\\d{2}
-2位数字[pa]m
-PM
或AM
[a-z]{3}
3个字母的空格\\)
-右括号。参见IDEONE demo:
String str = "( (Mon 3:23PM EDT) ( (Thu, Sep 3) ( (Thu, Sep 3) ( (Wed, Sep 2) ( (Tue, Sep 1) ( (Mon, Aug 31) ( (Fri, Aug 28) ( (Wed, Aug 26) ( (Wed, Aug 26) ( (Fri, Aug 21) ( (Mon, Aug 17) ( (Thu, Aug 13) ( (Thu, Aug 13)";
str = str.replaceAll("(?i)\\([a-z]{3} \\d{1,2}:\\d{2}[pa]m [a-z]{3}\\)", "(" + todaysDate + ")");
System.out.println(str);
今日输出:
( (Mon, Sep 07) ( (Thu, Sep 3) ( (Thu, Sep 3) ( (Wed, Sep 2) ( (Tue, Sep 1) ( (Mon, Aug 31) ( (Fri, Aug 28) ( (Wed, Aug 26) ( (Wed, Aug 26) ( (Fri, Aug 21) ( (Mon, Aug 17) ( (Thu, Aug 13) ( (Thu, Aug 13)