hi,
i have this homework problem where i need to use regex to remove every other character in a string.
in one part, i have to delete characters at index 1,3,5,.... i have done this as follows:
String s = "1a2b3c4d5";
System.out.println(s.replaceAll("(.).", "$1"));
this prints 12345
which is what i want. essentially i match two characters at a time, and replacing with the first character. i used group capturing to do this.
problem is i'm having trouble with the second part of the homework, where i need to delete characters at index 0,2,4,....
i have done the following:
String s = "1a2b3c4d5";
System.out.println(s.replaceAll(".(.)", "$1"));
this prints abcd5
, but the correct answer must be abcd
. my regex is only incorrect if the input string length is odd. if it's even, then my regex works fine.
i think i'm really close to the answer, but i'm not sure how to fix! please help!