Last active
December 21, 2023 15:31
-
-
Save kannangce/0ebf038b1f8c00edf657f6efca709c67 to your computer and use it in GitHub Desktop.
Custom string utilities.
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
/** | |
* Meant to contain the custom utilities related to string. Could be handy in common use cases. | |
**/ | |
public class StringUtils{ | |
/** | |
* Searches the given pattern in the given src string and applies the txr to | |
* the matches. | |
* <br/> | |
* <b>Note:</b> Ex, To convert snake case to camel case make the call, | |
* <br/> | |
* <i>findAndApply("some_snake_case", "_[a-z]",(x) -> x.replace("_","").toUpperCase())</i> | |
* | |
* @param src | |
* The string to be converted | |
* @param pattern | |
* the pattern for which the transformers to be applied. | |
* @param txr | |
* The transformers for the mathed patterns. | |
* @return The result after applying the transformation. | |
*/ | |
public static String findAndApply(String src, String pattern, | |
Function<String, String> txr) { | |
Matcher m = Pattern.compile(pattern).matcher(src); | |
StringBuilder sb = new StringBuilder(); | |
int last = 0; | |
while (m.find()) { | |
sb.append(src.substring(last, m.start())); | |
sb.append(txr.apply(m.group(0))); | |
last = m.end(); | |
} | |
sb.append(src.substring(last)); | |
return sb.toString(); | |
} | |
/** | |
* Converts the map as URL encoded string. | |
* | |
* @param map | |
* The {@link Map} to be converted as url encoded string. | |
* @return URL encoded string. | |
*/ | |
public static String asUrlEncodedString(Map<String, Object> map) { | |
return map.entrySet().stream() | |
.map(e -> e.getValue() == null | |
? e.getKey() | |
: e.getKey() + "=" + e.getValue().toString()) | |
.collect(Collectors.joining("&")); | |
} | |
public static List<String> findSubstringsMatchingPattern(String source, String pattern) { | |
return Pattern.compile(pattern).matcher(source).results().map(MatchResult::group).collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment