Kotlin 正则搜索与格式替换

Kotlin 正则搜索与格式替换

重点:并非简单的字符串替换,替换过程中需要用到匹配文本中的部分数据

正则表达式描述的是一个抽象的字符串,该字符串返回的具体字符串可能并不一样,在替换过程中需要用到这具体字符串的部分数据

本文通过一个字符串替换的小需求案例,介绍在kotlin中使用正则表达式搜索到相应的字符串,并进行格式替换,保留替换的部分数据。

0. 需求

  • 替换前数据, 该数据为一段字符串
	<p>1. Heat olive oil in a pan.</p>
    <p>2. Season chicken with salt.</p>
    <p>3. Add chicken to the pan and sear over high heat until brown on both sides.</p>
    <p>4. Add garlic into the pan and sautee until aromatic. Do not burn.</p>
    <p>5. Add coconut vinegar and simmer until fully reduced.</p>
    <p>6. Add 1 cup water, soy sauce, bay leaf, and black peppercorns.</p>
    <p>7. Turn down heat to medium and simmer for 12-15 minutes.</p>
    <p>8. Serve with a cup of brown rice and 1 tbsp atsara.</p>
  • 要求替换后为如下字符串数据
    <h6>Step 1</h6><p> Heat olive oil in a pan.</p>
    <h6>Step 2</h6><p> Season chicken with salt.</p>
    <h6>Step 3</h6><p> Add chicken to the pan and sear over high heat until brown on both sides.</p>
    <h6>Step 4</h6><p> Add garlic into the pan and sautee until aromatic. Do not burn.</p>
    <h6>Step 5</h6><p> Add coconut vinegar and simmer until fully reduced.</p>
    <h6>Step 6</h6><p> Add 1 cup water, soy sauce, bay leaf, and black peppercorns.</p>
    <h6>Step 7</h6><p> Turn down heat to medium and simmer for 12-15 minutes.</p>
    <h6>Step 8</h6><p> Serve with a cup of brown rice and 1 tbsp atsara.</p>

1. 需求分析

要将原本的在段落中的数字1,2,3… 等提取出来,改成Step 1, Step 2, Step 3…等,并给Step添加上head标签作为标题

2. 代码

 private fun formatCookMethods(cookMethodRawString: String): String {
        val regex = Regex("""<p>\d\.""")
        val foundMatches = regex.findAll(cookMethodRawString)
        var formatCookMethods: String = cookMethodRawString
        foundMatches.forEach { result ->
            formatCookMethods =
                formatCookMethods.replace(result.value, "<h6>Step ${result.value[3]}</h6><p>")
        }
        return formatCookMethods
    }

主要是使用Regex类对象的findAll方法,该方法返回了将所有匹配到字符串保存到了一个列表,列表的每个元素中包含了匹配到的具体字符串,从具体字符串中获取到需要的数据用以合成新的用来替换的字符串。

吐槽一下:kotlin的正则还是比java的正则好用些!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值