if else regex replace all

Viewed 134

Given a string like that:

"CSV;XML;ZIP"

I'm trying to make a regex to transform it to something like that:

".csv,.xml,.zip"

I tried this regex pattern : ([^;]*)(;|$) replace with: .\L$1,

but the result is : .csv,.xml,.zip,.,

I need my regex to satisfy :

  1. "CSV" -> ".csv"
  2. "CSV;XML;ZIP" -> ".csv,.xml,.zip"

I feel like I need to add something inside my regex which says: if it is the end of the string don't add ',' else do, but I don't know how to do it.

2 Answers

-- This is just another way to do it, that you can think about...

Like someone else already menitoned, in this case, you should think about going trough it with a loop. Split the Input by semicolon and process through it..

I'm using the Stream API in my solution

  1. lowercase the string
  2. Split the string by semicolon and create a stream out of the substrings
  3. Map toLowerCase
  4. Map ("." + element)
  5. Collect with StringJoiner - use comma as seperator
        String input = "CSV;ZIP;XML";
        String output = Arrays.stream(input.toLowerCase().split(";"))
                .map(s -> "." + s)
                .collect(Collectors.joining(","));

This solution works and in my opinion is much more readable than a regex

Demo:

String str = "CSV;XML;ZIP";

Pattern p = Pattern.compile("([^;]+)(;|$)");
Matcher m = p.matcher(str);

String replaced = m.replaceAll(
        match ->
        "." //in all cases replacement will start with dot
        + match.group(1).toLowerCase() //then lowercase ([^;]+)
        + (match.group(2).isEmpty() ? "" : ",") //then depending on (;|$) we decide if we add comma or not
);
System.out.println(replaced);

Output: .csv,.xml,.zip

Related