user972276
user972276

Reputation: 3053

parsing a simple date out of a string in java

In my program, the user should be able to specify a naming scheme. The naming scheme they specify should contain a simple date format like "yyyyMMdd", "MM-dd-yyyy", "yyyy/MM/dd", etc. I would prefer the order of the day, month, and year to not matter but can require a certain ordering (like year comes first followed by month followed by day). I would like to be able to easily retrieve this date out of the string in order to use it with the SimpleDateFormat class.

Here are some examples:

input string:    "abc?>@dyyyy-MM-dd-|(s*&d)"
output string:   "yyyy-MM-dd"

input string:    "daddy-MM/dd/yyyy-moMMy"
output string:   "MM/dd/yyyy"

Ultimately what I want to do is to replace (in the string the user provides) the date format specified with the current date.

If I wanted to fix it so the user can only enter year followed by month followed by day then I can do something like this:

String dateFormat = name.substring(name.indexOf("yyyy"), name.indexOf("dd") + 2)

but this means the user cannot use the String sequences "yyyy" and "dd" in the rest of the String or else this method would not work. This expression can also be represented by a regex but I dont know how to easily pull a substring that matches a regex out of a string.

Upvotes: 0

Views: 215

Answers (1)

Ωmega
Ωmega

Reputation: 43673

Use regex pattern

(MM|dd|yyyy)[\\/-]?(?!\\1)(MM|dd|yyyy)[\\/-]?(?!\\1)(?!\\2)(MM|dd|yyyy)

You might want to add some other separators you want to allow into [...] sections of the above pattern.

Upvotes: 2

Related Questions