0

I would like to find date from java string.But i can not able to do this please help

String : 01-02-2014 <2>
Ineed output like :01-02-2014

My code:

public String rejex(String idate){
 String result = null;
 try{
    String regex = "([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})";
    result = idate.replaceAll(regex, "$1-$2-$3");
 }catch(Exception e){}
    return result;

     }
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
user2601972
  • 47
  • 1
  • 6

3 Answers3

2

You are replacing what you are after (the date segments) with themselves.

If you want to extract it, this will work:

    String regex = "(([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})).*?<(\\d+)>";
    String str = "This is a random string 01-02-2014 <123> this is another part of that random string";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while(m.find())
    {
        System.out.println("Date: " + m.group(1));
        System.out.println("Number: " + m.group(6));
    }      

Yields:

Date: 01-02-2014
Number: 123
npinti
  • 51,780
  • 5
  • 72
  • 96
0

just extract \\d\\d-\\d\\d-\\d{4} out, let SimpleDateFormat do the parsing job.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • can i have regex code for this one – user2601972 Aug 06 '14 at 12:55
  • it's very hard to decide if the extracted string is a valid date with regex. E.g. `29-02-2000 (valid)` and `29-02-2013 (invalid)` the `\\d\\d....` in my answer is regex to extract the "date string". but you need check if it is a valid date by SimpleDateFormat. @user2601972 – Kent Aug 06 '14 at 13:32
0

if space is there all the time then it's simple.

 String dateStr = "01-02-2014 <2>"
 String dateSplit[] = dateStr.split(" ");
 //dateSplit[0] is what u are looking for

or

 String dateStr = "01-02-2014 <2>"
 String dateSplit[] = dateStr.split("<");
 //dateSplit[0].trim() is what u are looking for

and then simply use SimpleDateFormat to converting it into Date.

Vivek
  • 580
  • 2
  • 7
  • 26