I\'m trying to get the first letter of each word in a string using regex, here is what I have tried:
public class Test
{
public static void main(String[]
Sometimes it is easier to use a different technique. In particular, there's no convenient method for “get all matching regions” (you could build your own I suppose, but that feels like a lot of effort). So we transform to something we can handle:
String name = "First Middle Last";
for (String s : name.replaceAll("\\W*(\\w)\\w*\\W*","$1").split("\\B"))
System.out.println(s);
We could simplify somewhat if we were allowed to assume there were no leading or trailing non-word characters:
String name = "First Middle Last";
for (String s : name.replaceAll("(\\w)\\w*","$1").split("\\W+"))
System.out.println(s);