Last active
September 28, 2020 09:11
-
-
Save htsign/ae557870727bb7da665a92b6db64bdc6 to your computer and use it in GitHub Desktop.
replacement method with evaluator in java
This file contains hidden or 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.math.BigDecimal; | |
| import java.util.List; | |
| import java.util.function.BiFunction; | |
| import java.util.regex.Matcher; | |
| import java.util.regex.MatchResult; | |
| import java.util.regex.Pattern; | |
| import java.util.stream.Collectors; | |
| public class MyStringUtils { | |
| public static String replaceEx( | |
| final Pattern pattern, | |
| final String target, | |
| final BiFunction<MatchResult, String, String> evaluator | |
| ) { | |
| final var sb = new StringBuilder(); | |
| final Matcher matcher = pattern.matcher(target); | |
| final MatchResult result = matcher.toMatchResult(); | |
| while (matcher.find()) { | |
| matcher.appendReplacement(sb, evaluator.apply(result, target)); | |
| } | |
| matcher.appendTail(sb); | |
| return sb.toString(); | |
| } | |
| public static String toLocaleString(final int n) { | |
| return toLocaleString(BigDecimal.valueOf(n)); | |
| } | |
| public static String toLocaleString(final double d) { | |
| return toLocaleString(BigDecimal.valueOf(d)); | |
| } | |
| public static String toLocaleString(final BigDecimal d) { | |
| final var pattern = Pattern.compile("(?<=\\d)(?=(?:\\d{3})+(?!\\d))"); | |
| final BiFunction<MatchResult, String, String> callback = | |
| (m, s) -> !s.contains(".") || s.substring(m.start()).contains(".") ? "," : ""; | |
| return MyStringUtils.replaceEx(pattern, d.toString(), callback); | |
| } | |
| public static String toTitleCase(final String target, final String... ignoringWords) { | |
| final List<String> list = List.of(ignoringWords).stream() | |
| .map(String::toLowerCase) | |
| .collect(Collectors.toList()); | |
| final String replaced = MyStringUtils.replaceEx( | |
| Pattern.compile("([A-Za-z])([A-Za-z0-9]*)"), | |
| target, | |
| (m, s) -> { | |
| final String g = m.group(); | |
| return list.contains(g.toLowerCase()) | |
| ? g | |
| : m.group(1).toUpperCase() + m.group(2).toLowerCase(); | |
| }); | |
| return replaced.replace("_", ""); | |
| } | |
| public static String toSnakeCase(final String target) { | |
| return MyStringUtils.replaceEx( | |
| Pattern.compile("(?:[A-Z]{2,}(?=[A-Z])|[A-Z])"), | |
| target, | |
| (m, s) -> (m.start() == 0 ? "" : "_") + m.group().toLowerCase()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment