Regular Expression to find “lastname, firstname middlename” format

后端 未结 5 1779
挽巷
挽巷 2021-01-18 05:22

I am trying to find the format \"abc, def g\" which is a name format \"lastname, firstname middlename\". I think the best suited method is regex but I do not have any idea i

5条回答
  •  庸人自扰
    2021-01-18 06:04

    I would try and avoid a complicated regex, I would use String.substring() and indexOf(). That is, something like

    String name = "Last, First Middle";
    int comma = name.indexOf(',');
    int lastSpace = name.lastIndexOf(' ');
    String lastName = name.substring(0, comma);
    String firstName = name.substring(comma + 2, lastSpace);
    String middleName = name.substring(lastSpace + 1);
    System.out.printf("first='%s' middle='%s' last='%s'%n", firstName,
                middleName, lastName);
    

    Output is

    first='First' middle='Middle' last='Last'
    

提交回复
热议问题