Issue
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
Solution
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 ---^
Answered By - holi-java
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.