Remove Last instance of a character and rest of a string

后端 未结 4 977
予麋鹿
予麋鹿 2020-12-10 14:41

If I have a string as follows:

foo_bar_one_two_three

Is there a clean way, with RegEx, to return: foo_bar_one_two?

I know I

4条回答
  •  無奈伤痛
    2020-12-10 15:37

    I know is python, and my answer may be a little bit wrong in syntax, but in java you would do:

    String a = "foo_bar_one_two_three";
    String[] b = a.split("_");
    String c = "";
    for(int i=0; i

    Hope in python split function works same way. :)

    EDIT:

    Using the limit part of the function you can do:

    String a = "foo_bar_one_two_three";
    String[] b = a.split("_",StringUtils.countMatches(a,"_"));
    //and at this point, b is the array = [foo,bar,one,two]
    

提交回复
热议问题