Jos*_*ith 2 regex android kotlin
如果我有一个字符串,说,
"Hello, world!"
Run Code Online (Sandbox Code Playgroud)
和一个正则表达式方程是
"world".toRegex()
Run Code Online (Sandbox Code Playgroud)
我打电话
"Hello, world!".replace("world".toRegex(), "universe")
Run Code Online (Sandbox Code Playgroud)
我得到结果字符串
"Hello, universe!"
Run Code Online (Sandbox Code Playgroud)
这一切都按预期工作......但是如果我想保留我取出的那个字符串的副本怎么办?我想在变量中保留“世界”的副本。
您可以使用回调String#replace()方法并在其中分配一个变量:
var needle = ""
val result = "Hello, world!".replace("world".toRegex()) { needle = it.value; "universe" }
println("Replacement result: " + result)
println("Found match: " + needle)
Run Code Online (Sandbox Code Playgroud)
结果:
Replacement result: Hello, universe!
Found match: world
Run Code Online (Sandbox Code Playgroud)
请参阅在线 Kotlin 演示。
您可以使用 aMutableList<String>来保存匹配列表并将找到的匹配添加到其中:
var needle = mutableListOf<String>()
val result = "Hello, world! This world is too small.".replace("world".toRegex()) { needle.add(it.value); "universe" }
Run Code Online (Sandbox Code Playgroud)
结果:
Replacement result: Hello, universe! This universe is too small.
Found match: [world, world]
Run Code Online (Sandbox Code Playgroud)
请参阅另一个 Kotlin 演示。
| 归档时间: |
|
| 查看次数: |
3219 次 |
| 最近记录: |