You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何将仅含单个超链接的字符串拆分为多个片段

Kotlin 拆分含单个超链接的字符串实现

需求说明

给定仅包含单个<a>超链接的字符串,需要拆分为4个固定分段:

  • a[0]:超链接标签之前的文本内容
  • a[1]:超链接的href地址
  • a[2]:超链接的显示文本
  • a[3]:超链接标签之后的文本内容

输入输出示例如下:

Visit our <a href="http://www.google.net">website</a> for the latest news     ->  a[0]="Visit our "  a[1]="http://www.google.net"  a[2]= "website"  a[3]=" for the latest news"
Visit our <a href="http://www.google.net">website</a>                         ->  a[0]="Visit our "  a[1]="http://www.google.net"  a[2]= "website"  a[3]=""
<a href="http://www.google.net">website</a>  for the latest news              ->  a[0]=""           a[1]="http://www.google.net"  a[2]= "website"  a[3]=" for the latest news"
Visit our <a href="#">website</a> for the latest news                         ->  a[0]="Visit our "  a[1]="#"                      a[2]= "website"  a[3]=" for the latest news"

实现方案

因为输入场景固定(仅含单个标准格式a标签),无需引入额外HTML解析依赖,用正则匹配即可实现,代码轻量高效:

fun splitSingleLinkContent(input: String): List<String> {
    // 正则匹配a标签结构,捕获前后文本、href地址、链接文本四个分组
    val regex = Regex("""^(.*?)<a\s+href="([^"]+)">([^<]*)</a>(.*)$""", RegexOption.DOT_MATCHES_ALL)
    val matchRes = regex.find(input) ?: error("输入内容不符合单个超链接的格式要求")
    // 丢弃第0位的全量匹配结果,剩余4个元素就是目标分段
    return matchRes.groupValues.drop(1)
}

验证测试

可以通过以下代码验证所有示例场景,输出和预期完全一致:

fun main() {
    val testSamples = listOf(
        "Visit our <a href=\"http://www.google.net\">website</a> for the latest news",
        "Visit our <a href=\"http://www.google.net\">website</a>",
        "<a href=\"http://www.google.net\">website</a>  for the latest news",
        "Visit our <a href=\"#\">website</a> for the latest news"
    )
    testSamples.forEach { content ->
        val segments = splitSingleLinkContent(content)
        segments.forEachIndexed { idx, seg ->
            print("a[$idx]=\"$seg\"  ")
        }
        println()
    }
}

注意事项

  • 该实现仅针对题目约定的单个标准格式a标签场景,不做复杂HTML容错。如果后续输入可能出现嵌套标签、多属性、非标准引号、转义字符等复杂HTML内容,建议使用专门的HTML解析库处理,避免正则解析HTML的兼容性问题。
  • 如果需要适配href用单引号包裹、href属性不在a标签第一个位置等场景,按需调整正则规则即可。

内容的提问来源于stack exchange,提问作者HelloCW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 06:45:31