Swift替换字符串中的多个字符 [英] Swift Replace Multiple Characters in String
问题描述
下面是我用来用回车符替换HTML break标记的以下代码行。但是,我还需要替换其他HTML符号,当我再次调用这行代码时,使用不同的参数,就像第一个被覆盖一样。有没有办法可以包含多个参数?在Swift中有更有效的方法吗?例如:将br>替换为,将nbsp替换为。
Below is the following line of code I use to replace an HTML break tag with a carriage return. However, I have other HTML symbols that I need to replace and when I call this line of code again, with different parameters, it's as if the first one is overwritten. Is there a way I can include multiple parameters? Is there a more efficient way to do this in Swift? For example: replace both br> with "" and nbsp with "".
textView.text = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r")
推荐答案
使用 replacementOccurrences 以及 String.CompareOptions.regularExpresion 选项。
示例(Swift 3):
Example (Swift 3):
var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)
输入要在方括号内替换的字符,如此[ \\字符]
Input characters which are to be replaced inside the square brackets like so [\\ Characters]
输出:
7Hello, 7play7ground777
这篇关于Swift替换字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!