0

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.

user972276
  • 2,973
  • 9
  • 33
  • 46
  • You can pull results out of a regex by using [Capture Groups](http://stackoverflow.com/questions/6865377/java-regex-capture-group). – ean5533 Oct 16 '12 at 16:28
  • I would suggest less generic symbols; something more along the lines of %Y to represent year, %m to represent month, %d to represent days? – Asad Saeeduddin Oct 16 '12 at 16:30

1 Answers1

2

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.

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • @Asad - Because you have deleted you answer, you should delete now also the comment above, as other users will not understand it... – Ωmega Oct 16 '12 at 16:46
  • Thanks! that regex works but how do I use it to retrieve this substring from the whole string? My String will be of thew format ".*(MM|dd|yyyy)[\\/-]?(?!\\1)(MM|dd|yyyy)[\\/-]?(?!\1)(?!\2)(MM|dd|yyyy).*" and I just want the part of the string that matches the regex – user972276 Oct 16 '12 at 16:49
  • @user972276 - read http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex – Ωmega Oct 16 '12 at 16:56