Created
September 22, 2019 15:17
-
-
Save Zanoshky/22820007d12093390c264306669f898e to your computer and use it in GitHub Desktop.
Java code to replace minutes in SQL File to the closest quarter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.List; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class RegexToReplaceMinutesToClosestQuarter { | |
private static final String FILE_PATH_DEMO = "E:\\work\\workbook-db\\database\\demo.sql"; | |
private static final String REGEX_FOR_MINUTES = ":[0-9][0-9]'"; | |
public static void main(final String[] args) { | |
final Path path = Paths.get(FILE_PATH_DEMO); | |
try (Stream<String> lines = Files.lines(path)) { | |
List<String> replaced = getReplacedLines(lines); | |
Files.write(path, replaced); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static List<String> getReplacedLines(final Stream<String> lines) { | |
return lines.map(line -> { | |
Pattern pattern = Pattern.compile(REGEX_FOR_MINUTES); | |
Matcher m = pattern.matcher(line); | |
StringBuffer stringBuffer = new StringBuffer(line.length()); | |
while (m.find()) { | |
String text = stripOutExtraCharactersFromNumber(m.group(0)); | |
int number = parseToInt(text); | |
String result = roundToQuarter(number); | |
m.appendReplacement(stringBuffer, Matcher.quoteReplacement(result)); | |
} | |
m.appendTail(stringBuffer); | |
return stringBuffer.toString(); | |
}).collect(Collectors.toList()); | |
} | |
private static String roundToQuarter(final int number) { | |
if (number <= 7) { | |
return ":00'"; | |
} else if (number <= 22) { | |
return ":15'"; | |
} else if (number <= 37) { | |
return ":30'"; | |
} else if (number <= 52) { | |
return ":45'"; | |
} else { | |
return ":00'"; | |
} | |
} | |
private static Integer parseToInt(final String text) { | |
return Integer.valueOf(text); | |
} | |
private static String stripOutExtraCharactersFromNumber(final String text) { | |
return text.substring(1, 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment