Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a String by "-" only when the following character is a digit and the previous one is a letter? Java/Scala

I want to find a way to split a string by a "-" only for certain cases.

I want to split if the previous character is a letter (small or capital) and if it is the not the first character in the string. And the following character must be a digit [0-9]. There is no space in the string.

-11 => List(-11)
v-11 => List(v,11)
v- => List(v-)
-2-11 => List(-2-11)
v-11- => List(v,11-)
-v-11- => List(-v,11-)

I wasn't able to do it properly with String.split(regex). The only solution I found was to parse the whole String and look for each characters. Is there a regex for that?

Thanks for your help.

like image 965
dbaq Avatar asked Dec 06 '25 20:12

dbaq


1 Answers

try split the string with this regex:

"(?<=[A-Za-z])-(?=\\d+)"

add a test class:

@Test
public void atest() {
    String re = "(?<=[A-Za-z])-(?=\\d+)";
    String[] ss = new String[] { "-11", "v-11", "v-", "-2-11", "v-11-", "-v-11-" };
    for (String s : ss) {
        System.out.println(s + " => " + Arrays.toString(s.split(re)));
    }
}

outputs:

-11 => [-11]
v-11 => [v, 11]
v- => [v-]
-2-11 => [-2-11]
v-11- => [v, 11-]
-v-11- => [-v, 11-]
like image 143
Kent Avatar answered Dec 08 '25 10:12

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!