假设您有一个字符串http://server.com/s123456
,并且想要从中获取123456
。或http://server.com/s123456&a=100
并获取123456,100。要在其中包含字符串部分的许多不同情况。
为了匹配字符串,我使用正则表达式。
@Test
fun test() {
val text = "http://server.com/s123456" // Source string.
val reg = "^http://server.com/s\\d+\$".toRegex()
assertEquals(true, reg.matches(text))
// Try to split the string with findAll().
val a: Sequence<MatchResult> = reg.findAll(text, 0)
val names = a.map { it.groupValues[0] }.joinToString()
println(names) // http://server.com/s123456
}
但是它不会将源字符串拆分为字符和数字,只是打印:
http://server.com/s123456
。有没有一种写掩码的方法,以便我们可以从字符串中检索数字(或其他任何部分)?
最佳答案
您需要在感兴趣的部分周围使用捕获组。使用此"^http://server.com/s(\\d+)\$"
并使用it.groupValues[1]
。
关于regex - 如何通过Kotlin或Java中的正则表达式获取字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60264832/