在分隔符 - 正则表达式之间替换字符串中的字符

时间:2015-09-07 21:00:29

标签: java regex string

我似乎无法想出这个。我知道可以使用正则表达式,但是没有任何创建它们的经验。我有一串日期,如下所示:

( (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());

1 个答案:

答案 0 :(得分:2)

您可以将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 - PMAM
  • [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)