Sharath Bhaskara
Sharath Bhaskara

Reputation: 497

Need help in finding a regex in Java to capture date with all formats in a string

I have a string with format given below, i want to capture the date from this string and then later parse it with a proper date format.

sometext username, 19/05/1985: some more text
sometext username2, 19-Sep-1985 23:59:59: some more text

Assumptions:

  1. username will always succeeded by a coma ","
  2. A date always ends with a colon
  3. There may more text before and after the username and date strings.

Upvotes: 0

Views: 61

Answers (2)

Sharath Bhaskara
Sharath Bhaskara

Reputation: 497

Since my problem is unsolveable, and is more generic in nature. I had to change the input to HTML format. Something like <b>username, 19-sep-2015 23:59:59:</b>.

After doing this I was able to parse the date by capturing ,\s+(.*):< and removing the last colon.

Upvotes: 0

Durgpal Singh
Durgpal Singh

Reputation: 11953

Use pattern-matcher to extract the date
Use (?<=\w*, ).*(?=:) as pattern to extract date and dd/mm/yyyy as date format

String str = "sometext username, 19/05/1985: some more text";
Pattern p = Pattern.compile("(?<=\\w*, )\\d{2}/\\d{2}/\\d{4}(?=:)");
Matcher m = p.matcher(str);
m.find();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
System.out.println(sdf.parse(m.group()));

Output :

Sat Jan 19 00:05:00 IST 1985

Upvotes: 1

Related Questions