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的正则好用些!