使用REGEX输入简单字符串分割Java空的第一个元素

时间:2019-01-18 15:03:18

标签: java regex split

我在2个不同的在线验证器(用于Java)上验证了此Java REGEX,它似乎可以在一个和两个元素的姓氏上使用。但是,split中的第一个元素始终为null-我在做什么错?我有一个解决方法,但显然它不是很专业..感谢您的见识

String strVal = "Daly Oslen, Krysta Patrolman Second Sector";
//String strVal = "Oslen, Krysta Patrolman Second Sector";
String[] values2 =  strVal.split("(.*),\\s{0,2}(\\w+)");

System.out.println(" strVal=" +  strVal);
System.out.println("values2[0]=" + values2[0]);
System.out.println("values2[1]=" + values2[1]);  

values2[0]= strVal.replace(values2[1], "");
System.out.println("new values2[0]=" + values2[0]);

================================================================
strVal=Daly Oslen, Krysta Patrolman Second Sector
values2[0]=
values2[1]= Patrolman Second Sector
new values2[0]=Daly Oslen, Krysta

ADDED :  Thanks for the reply. The regex   (.*),\s{0,2}(\w+)   does select 
"Daly Oslen, Krysta" in the validators, if I check the length of values2 it 
 is indeed 2, it's acting like it finds nothing before my search term, so 
 Java split is working correctly and maybe is not the tool I want?  

    Pattern p = Pattern.compile("(.*),\\s{0,2}(\\w+)");
    Matcher m = p.matcher(strVal);
    if (m.find()) {
        System.out.println("m=" + m);
        System.out.println("m.group(0)" + m.group(0));
    } else {
        System.out.println("no match");
    }

    Here's the output - check out how println m prints out!

    m=java.util.regex.Matcher[pattern=(.*),\s{0,2}(\w+) region=0,42 
                           lastmatch=Daly Oslen, Krysta]

     m.group(0)Daly Oslen, Krysta

0 个答案:

没有答案