【问题标题】:IOS How to get String.range(of:string) multiple in swiftIOS如何在swift中获取多个String.range(of:string)
【发布时间】:2018-12-12 16:53:16
【问题描述】:

MyText 是

let myString: NSAttributedString = <siren> 123123 <siren> 123123 <siren>
let myRange = myString.string.range(of:"<siren>")
let newString = NSMutableAttributedString()
newString.append(myString)
if myRange != nil{
  newString.replaceCharacters(in: NSRange(myRange, in:myString.string), 
            with:myAttributeString as NSAttributedString!)
}

如果myString 有一个&lt;siren&gt;,这是可行的,但是当它有两个以上&lt;siren&gt; 时,它就不起作用了

只替换第一个&lt;siren&gt;

我认为String.range 返回第一个值

如何找到它们?

【问题讨论】:

  • a) 这不是工作代码。 b) 不要以大写字母开头变量,这使得从变量中确定类变得困难。请更新
  • 使用字符串,然后将其转换为属性字符串

标签: ios swift swift3 nsmutablestring


【解决方案1】:

如果你想找到所有范围,你可以尝试使用这个问题的解决方案get all ranges of a substring in a string in swift

但如果您的主要目的是替换某些字符串/模式的出现,您可以添加这样的扩展:

extension String {

  func replacing(pattern: String, withTemplate: String) throws -> String {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    return regex.stringByReplacingMatches(in: self,
                                          options: [],
                                          range: NSRange(0 ..< utf16.count),
                                          withTemplate: withTemplate)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多