Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
we have files that we are reading and trying to rename in some scenarios and below code works..
files --
String regex = "[0-9]{4}[_-][0-9]{2}[_-][0-9]{2}"; java.util.regex.Matcher m = java.util.regex.Pattern.compile(regex).matcher(context.CurrentFileName); if (m.find()) { context.CurrentFileDate = "datefolder="+(m.group(0).trim().substring(0,4))+"-"+(m.group(0).trim().substring(5,7))+"-"+(m.group(0).trim().substring(8,10)); } else { context.CurrentFileDate = "datefolder="+formattedDate; }
now we are getting interesting file-names and needed some help how i can modify above if-else statement so it can work.
files --
any suggestion how to modify above if-else statement ? since matcher in java can only find based on regex, in what i tried so far .
Hello,
Instead of extending multiple if-else blocks, the recommended approach is to extract YYYY / MM / DD independently using regex, then build the date based on what is present. This keeps the logic simple and scalable.
Example (tJava-compatible):
String filePath = context.CurrentFileName;
String year = null;
String month = "01";
String day = "01";
// Match YYYY=2029
java.util.regex.Matcher y =
java.util.regex.Pattern.compile("YYYY=(\\d{4})").matcher(filePath);
if (y.find()) {
year = y.group(1);
}
// Match MM=03
java.util.regex.Matcher m =
java.util.regex.Pattern.compile("MM=(\\d{2})").matcher(filePath);
if (m.find()) {
month = m.group(1);
}
// Match DD=22
java.util.regex.Matcher d =
java.util.regex.Pattern.compile("DD=(\\d{2})").matcher(filePath);
if (d.find()) {
day = d.group(1);
}
// Fallback: date inside filename (2025-01-01 or 2025_01_01)
if (year == null) {
java.util.regex.Matcher f =
java.util.regex.Pattern.compile("(\\d{4})[_-](\\d{2})[_-](\\d{2})")
.matcher(filePath);
if (f.find()) {
year = f.group(1);
month = f.group(2);
day = f.group(3);
}
}
// Final fallback
if (year == null) {
context.CurrentFileDate = "datefolder=" + formattedDate;
} else {
context.CurrentFileDate =
"datefolder=" + year + "-" + month + "-" + day;
}
Why this works well:
Avoids deep if-else chains
Handles partial paths (YYYY, YYYY/MM, YYYY/MM/DD)
Safely defaults missing month/day to 01
Still supports dates embedded in filenames
Best practice:
When filename patterns evolve, extract each date component independently and compose the final value, rather than trying to match all cases in a single regex.
Thanks,
Gourav
Hi,
This approach also makes it easy to support future filename or folder variations, since each date component is handled independently. Missing values safely default to 01, avoiding additional conditional logic.
If this solution addresses the requirement, please mark it as Accepted Solution.
Thanks,
Gourav