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.
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-]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With