Why is Kotlin String.split with a regex string not the same as Java?

Ilya Fedoseev :

I have the following Java code:

String str = "12+20*/2-4";
List<String> arr = new ArrayList<>();

arr = str.split("\\p{Punct}");

//expected: arr = {12,20,2,4}

I want the equivalent Kotlin code, but .split("\\p{Punct}") doesn't work. I don't understand the documentation here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/split.html

holi-java :

you should using String#split(Regex) instead, for example:

val str = "12+20*/2-4";
val arr = str.split("\\p{Punct}".toRegex());
//  ^--- but the result is ["12","20","","2","4"]

val arr2 = arr.filter{ !it.isBlank() };
//  ^--- you can filter it as further, and result is: ["12","20","2","4"]

OR you can split more Punctuations by using \\p{Punct}+ , for example:

val arr = str.split("\\p{Punct}+".toRegex())
//  ^--- result is: ["12","20","2","4"]

OR invert the regex and using Regex#findAll instead, and you can find out the negative numbers in this way. for example:

val str ="12+20*/2+(-4)";

val arr ="(?<!\\d)-?[^\\p{Punct}]+".toRegex().findAll(str).map{ it.value }.toList()
//  ^--- result is ["12","20","2","-4"]
//   negative number is found   ---^

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=435237&siteId=1