为什么在Kotlin中用正则表达式字符串分割的字符串与Java不一样?

我有以下Java代码:

String str = "12+20*/2-4"; List<String> arr = new ArrayList<>(); arr = str.split("\\p{Punct}"); //expected: arr = {12,20,2,4} 

我想要相当于Kotlin的代码,但是.split("\\p{Punct}")不起作用。 我不明白这里的文档: https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/split.html

你应该使用String#split(Regex)来代替,例如:

 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"] 

或者,您可以使用\\p{Punct}+分隔更多的标点符号 ,例如:

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

或者 反转正则表达式,使用Regex#findAll代替,你可以通过这种方式找到负数。 例如:

 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 ---^ 

正如在这个问题中提到的, Kotlin中的大多数字符串操作方法都被重载,以便同时使用原始字符串和正则表达式。 (这个问题谈论replace但它是相同的想法split )。 目前split是把第一个反斜线当作一个转义字符,而不是将其识别为正则表达式。

你可以在你的调用中添加一个toRegex()调用或Regex包装来split

 val str = "12+20*/2-4"; str.split("\\p{Punct}".toRegex()) //this str.split("Regex(\\p{Punct}")) //or this 

正如@ holi-java在他们的回答中提到的那样,它将匹配*/ giving ["12","20","","2","4"]之间的空字符串。 你可以使用"\\p{Punct}+"作为你的正则表达式来避免这种情况。 (尽管注意Java除了包含+还给出了这个空字符串的输出。)

你可以打电话

 str.split(Regex("{\\p{Punct}")) 
Interesting Posts