I have a string (which is basically a file name following a naming convention) abc.def.ghi
I would like to extract the substring before the first
Here is code which returns a substring from a String until any of a given list of characters:
/**
* Return a substring of the given original string until the first appearance
* of any of the given characters.
*
* e.g. Original "ab&cd-ef&gh"
* 1. Separators {'&', '-'}
* Result: "ab"
* 2. Separators {'~', '-'}
* Result: "ab&cd"
* 3. Separators {'~', '='}
* Result: "ab&cd-ef&gh"
*
* @param original the original string
* @param characters the separators until the substring to be considered
* @return the substring or the original string of no separator exists
*/
public static String substringFirstOf(String original, List characters) {
return characters.stream()
.map(original::indexOf)
.filter(min -> min > 0)
.reduce(Integer::min)
.map(position -> original.substring(0, position))
.orElse(original);
}