j1nrg
j1nrg

Reputation: 69

Replacing characters in a string between delimiter - Regex

I can't seem to figure this one out. I know that a regular expression can be used, but haven't really had any experience with creating them. I have a string of dates that looks like this:

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

When there is a time stamp in the string, such as the 3:23 above, I need to replace that with the today's date. I am getting today's date in the format I need by using the following:

Calendar cal = Calendar.getInstance();
SimpleDateFormat necessaryFormat = new SimpleDateFormat("EE, MMM dd");
String todaysDate = necessaryFormat.format(cal.getTime());

Essentially the string should be

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

So far I have tried to use something along the lines of this, but all it is doing is removing the first piece of the string between the parenthesis:

String origStr = links.text().substring(0, links.text().indexOf("("))+
            links.text().substring(links.text().indexOf(")")+"))".length());

Upvotes: 1

Views: 57

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

You can use a replaceAll with the following regex:

(?i)\\([a-z]{3} \\d{1,2}:\\d{2}[pa]m [a-z]{3}\\)

Regex breakdown:

  • (?i) - Make the pattern case-insensitive
  • \\( - a literal opening round bracket
  • [a-z]{3} - 3 letters
  • \\d{1,2}: - a space, 1 or 2 digits, and a :
  • \\d{2} - 2 digits
  • [pa]m - PM or AM
  • [a-z]{3} a space with 3 letters
  • \\) - a closing round bracket.

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

Today's output: ( (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)

Upvotes: 2

Related Questions