1

I want to change a date string from YYYY-MM-DD format to DD.MM.YYYY format using regex. Here is my implementation:

String date = "2008-12-30"; //30th Dec, 2008 
String searchPattern = "(\\d{4})-(\\d\\d)-(\\d\\d)";

//Implementing the Pattern from searchPattern
Pattern pattern = Pattern.compile(searchPattern);

Matcher matcher = pattern.matcher(date);
String newDate = "";

if(matcher.find())
{
    //Functions          
    newDate = matcher.replaceFirst(matcher.group(3)+"."+matcher.group(2)+"."+matcher.group(1));
    //Issue with group text
    // newDate = matcher.replaceFirst("\3.\2.\1");
}

If I use captured groups like \1,\2 etc, the output contains funny text. So, the problem in a nutshell is:

matcher.group(1) functions \1 returns funny text

5
  • Where "funny text" is.....
    – awksp
    May 23, 2014 at 10:25
  • Why you use regex not DateFormat?
    – Jens
    May 23, 2014 at 10:28
  • characters as symbols with question marks May 23, 2014 at 10:29
  • i am making an exercise for a course May 23, 2014 at 10:30
  • Your example seems to work "fine" with the arguments provided.
    – Mena
    May 23, 2014 at 10:50

2 Answers 2

0

As others already said using a DateFormat is better suited for the purpose and probably you already got the solution to your problem. But then when I tried to running your code and indeed I was able to replicate what you have mentioned.

Surprisingly I got different characters depending where the output was streamed. The output has nothing to do with your regex expr. whatsoever and you can get the same by writing something as simple as

System.out.println((char) 3 + "." + (char) 2 + "." + (char) 1);

Here code points 3, 2 and 1 are interpreted differently, depending on the context where they are used. They may be interpreted as control characters ETX, STX and SOH respectively or graphical symbols if used on a video display device.

Output at my eclipse:
└.┐.┌
(Eclipse console is probably mapping to wrong Windows Glyph List 4 characters)

Output at DOS:
♥.☻.☺
(Here Code page 437 is at use)

0

Why not just:

String newDate = date.replaceAll("(\\d{4})-(\\d\\d)-(\\d\\d)", "$3.$2.$1");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.