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.

2
  • You can pull results out of a regex by using Capture Groups. Commented Oct 16, 2012 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? Commented Oct 16, 2012 at 16:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Asad - Because you have deleted you answer, you should delete now also the comment above, as other users will not understand it...
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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.