Get the first letter of each word in a string using regex

后端 未结 6 1000
天命终不由人
天命终不由人 2021-01-13 04:10

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[]         


        
6条回答
  •  灰色年华
    2021-01-13 04:21

    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);
    

提交回复
热议问题