How to convert a string with extra characters
String str = "file-09-01-2024"
pattern = "dd-MM-YYYY"
using SimpleDateFormat with pattern = "dd-MM-YYYY"
I don't know how many extra symbols there can be
What if the extra characters are at the end? What if you don't know where it is? "file-09-01-2024-version1" "09-01-2024-index" "09-01-2024" All we know is that the date is in the String, but we don’t know where
Use a regex to extract the
dd-MM-YYYYpart. A simple regex to match it could be\d{2}-\d{2}-\d{4}. This matches 2 digits, a hyphen, 2 digits, a hyphen and then 4 digits. You can test it on regex101 : https://regex101.com/r/socnHp/1.Example:
Note
The regex I provided will still match incorrect dates, like 09-14-2024. I believe in for your use case it's fine but if you need stricter validation, you can check similar questions on this site, for example this one.