I think you could do this with regular expressions, by looking at where the matches start and end. However, it seems like in this case regular expressions are overkill. It is simpler to allocate a new character array, copy the first and last character of the input to that array, and the fill in the middle with underscores, then allocate a string from that character array, like so:
public class ReplaceMiddle {
public static String replaceMiddle (String s) {
char[] c = new char[s.length()];
c[0] = s.charAt(0);
for (int i = 1; i < s.length() - 1; i++) {
c[i] = '_';
}
c[s.length() - 1] = s.charAt(s.length() - 1);
return new String(c);
}
public static void main(String[] argv) {
System.out.println( ReplaceMiddle.replaceMiddle("I want a pumpkin."));
}
}
Output:
I_______________.
Note that this does not handle zero length strings, or the case of s being null.