Home > Software design >  How to only remove one character if there are two consecutive characters in the string (using regex)
How to only remove one character if there are two consecutive characters in the string (using regex)

Time:12-13

I have a list of list of Characters like this : [[P, A, H, N, ,], [A, P, L, S, I, I, G, ,], [Y, I, R]].

Output expected as a String of every character in the list of list of Characters

Output expected: "PAHN,APLSIIG,YIR".

My code

String str = "";
//code#1
for(int j=0; j<list.size(); j  ){
   str  = Arrays.toString(list.get(j).toArray(new Character[0])).replaceAll("[\\]\\[,]", 
   "").replaceAll(" ", "");
}

str in code#1 : "PAHNAPLSIIGYIR"

List to a String

String str = "";

//code#2, converts a list into String
for(int j=0; j<list.size(); j  ){
   str  = Arrays.toString(list.get(j).toArray(new Character[0])).replaceAll(" ", "");
}

str in code#2 : [P,A,H,N,,][A,P,L,S,I,I,G,,][Y,I,R]

Check this code to understand better: [https://onecompiler.com/java/3xm55ywr6][1]

My Problem

String in code#2 have two consecutive ',' characters, as can be seen after characters 'N' and 'G', how to just replace only one ',' character if there are two ',' coming together???

CodePudding user response:

If you need to flat your lists

private static String flatLists(List<List<String>> asList) {
        return asList.stream()
                .flatMap(List::stream)
                .filter(s -> !s.equals(" "))
                .collect(Collectors.joining());
    }

OUTPUT:

PAHNAPLSIIGYIR

CodePudding user response:

I am not sure I fully understood your question

However, if your goal is to remove all the commas, spaces, and square brackets, then the following regular expression should work

[\[\],\s]

You can test it here

https://regex101.com/r/j0OIOH/1

  • Related