如何在Swift中使用组替换字符串中的出现? [英] How to replace occurences in string using groups in Swift?

查看:76
本文介绍了如何在Swift中使用组替换字符串中的出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要替换:

< p> < div>

\ n< p> \ n< div>

用一个单一模式替换.有可能吗?

in string with one single pattern replacing. Is it possible?

let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>", with: "\n<p>").replacingOccurrences(of: "<div>", with: "\n<div>")

使用正则表达式有更好的解决方案吗?

is there a better solution with regex?

推荐答案

您可以执行正则表达式搜索,并在其中替换一个模板字符串:

You can do a regular expression search, with a template in the replacement string:

let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>|<div>", with: "\n$0", options: .regularExpression)

对于每个匹配,将 $ 0 模板替换为与该模式实际匹配的模板.

For each match, the $0 template is replaced by what actually matched the pattern.

这篇关于如何在Swift中使用组替换字符串中的出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆