iosswiftswift3nsmutablestring

IOS How to get String.range(of:string) multiple in swift


MyText is

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!)
}

If myString has one <siren> this is worked, but it's not worked when it has more then two <siren>

replace only first <siren>

I think String.range return first value

how to find them all?


Solution

  • If you want to find all ranges you can try to use solution from this question get all ranges of a substring in a string in swift

    but if your main purpose of that is replacing the occurrence of some string/pattern you can add an extension like that:

    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)
      }
    }