Android Kotlin正则表达式替换子字符串,获取被替换的子字符串

4
如果我有一个字符串,比如说,

"Hello, world!" 

还有一个正则表达式的方程式,它是:

"world".toRegex()

并且我称之为

"Hello, world!".replace("world".toRegex(), "universe")

我获得了结果字符串。
"Hello, universe!"

这一切都按预期运行...但是如果我想要保留我取出的字符串的副本呢?我想在一个变量中保留"world"的副本。

2个回答

10
您可以使用回调函数来调用 String#replace() 方法,并在其中分配一个变量:
var needle = ""
val result = "Hello, world!".replace("world".toRegex()) { needle = it.value; "universe" }
println("Replacement result: " + result)
println("Found match: " + needle)

结果:

Replacement result: Hello, universe!
Found match: world

请查看在线 Kotlin 演示

您可以使用 MutableList<String> 来保存匹配项列表并将找到的匹配项添加到其中:

var needle = mutableListOf<String>()
val result = "Hello, world! This world is too small.".replace("world".toRegex()) { needle.add(it.value); "universe" }

结果:

Replacement result: Hello, universe! This universe is too small.
Found match: [world, world]

查看另一个Kotlin演示


我喜欢你的解决方案。但是它并没有帮助我使用正则表达式 (\d{1,4})(\d{1,6})?(\d{1,5})? 将字符串 343434343434343 替换为 3434-343434-34343。你有什么想法吗? - Jimit Patel
1
@JimitPatel 这是另一回事。请尝试 https://rextester.com/IOLL50071。虽然我不知道为什么您要选择匹配最后两个组。 - Wiktor Stribiżew
@WiktorStribiżew,你的解决方案很棒。只是我使用的是replaceFirst而不是replace,可选组是因为字符串的大小是可变的,基本上是卡号。 - Jimit Patel

-1
val str = "Hello, world!"
val regex = "world".toRegex()
val matchResult = regex.find(str)
val match = matchResult?.value.orEmpty()
val replaced = str.replace(regex,"universe")

1
这个答案有什么问题吗?只是它不在一行里吗? - Nisba
3
我不是那个点踩者,但我可以猜测一下:(1)这个代码在输入上做了两次遍历,以及(2)通常只提供代码的答案会被人们嫌弃。即使代码对你来说似乎非常明显,稍微解释一下或者附上一个文档链接都能让答案更高质量。此外,(3)有时候点踩也可能因为毫无根据的原因,您不必担心。 - ggorlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接