MST
星途 面试题库

面试题:Kotlin正则表达式之替换与分组高级应用

给定一个复杂的HTML片段字符串,例如 "<p class='content'>Some text <a href='http://example.com'>link</a> more text</p>",使用Kotlin正则表达式提取所有的链接(即 <a href='...'> 标签中的链接部分),并将其替换为纯文本形式,例如 "Some text http://example.com more text"。要求通过分组和替换功能实现,编写完整的Kotlin代码。
18.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
fun main() {
    val htmlFragment = "<p class='content'>Some text <a href='http://example.com'>link</a> more text</p>"
    val pattern = "<a href='([^']+)'>.*?</a>".toRegex()
    val result = pattern.replace(htmlFragment) { matchResult ->
        matchResult.groupValues[1]
    }
    println(result)
}