Use Java regex to delete every other character in the string
I have this homework problem. I need to use regular expressions to delete every other character in the string
On the one hand, I have to delete the characters on indexes 1, 3 and 5. I have done the following:
String s = "1a2b3c4d5"; System.out.println(s.replaceAll("(.).","$1"));
This print is 12345. This is what I want Basically, I match two characters at a time and replace with the first character I use group capture to do this
The problem is, I have trouble in the second part of the job. I need to delete the characters of index 0,2,4
I did the following:
String s = "1a2b3c4d5"; System.out.println(s.replaceAll(".(.)","$1"));
This prints ABCD 5, but the correct answer must be ABCD If the length of the input string is odd, my regular expression is incorrect If it is average, then my regular expression works normally
I think I'm really close to the answer, but I don't know how to solve this problem
Solution
You're really close to the answer: just match the second char
String s = "1a2b3c4d5"; System.out.println(s.replaceAll(".(.)?","$1")); // prints "abcd"
This is because:
>By default, the regular expression is greedy. If it is there, it will occupy the second character
>When you enter an odd length of, the second character will not be replaced at the last time, but you will still match one character (that is, the last character in the input)
>Even if the group cannot match, you can still replace it with a backreference
>It will be replaced with an empty string instead of "null" > this is the same as matcher Unlike group (int), it returns null for the failed group
reference resources
> regular-expressions. info/Optional
Take a closer look at the first part
Let's take a closer look at the first part of the lesson:
String s = "1a2b3c4d5"; System.out.println(s.replaceAll("(.).","$1")); // prints "12345"
You don't have to use it here? For the second character, but it "works", because even if you don't match the last character, you don't have to! Due to the problem specification, the last character can remain unparalleled and not replaced
Now suppose we want to delete the characters on index 1,5... And put the characters with index 0,4... In parentheses
String s = "1a2b3c4d5"; System.out.println(s.replaceAll("(.).","($1)")); // prints "(1)(2)(3)(4)5"
A-HA! Now, you have exactly the same problem as odd input! Your last character does not match your regular expression, because your regular expression needs two characters, but only one character is the input of odd length!
The solution is to make the matching second char optional again:
String s = "1a2b3c4d5"; System.out.println(s.replaceAll("(.).?","($1)")); // prints "(1)(2)(3)(4)(5)"