-2

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?

Sanket Ray
  • 1,071
  • 1
  • 15
  • 24
Adam
  • 325
  • 1
  • 4
  • 20
  • 3
    a) this isn't working code. b) don't start variables with uppercase letters, it makes it hard to determine classes from variables. Please update – Ashley Mills Jul 04 '18 at 09:39
  • 1
    Possible duplicate of [Swift find all occurrences of a substring](https://stackoverflow.com/questions/40413218/swift-find-all-occurrences-of-a-substring) – Larme Jul 04 '18 at 09:42
  • Work with string then covert it to attributed string – Inder Kumar Rathore Jul 04 '18 at 09:44

1 Answers1

3

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)
  }
}
Piotr Labunski
  • 1,638
  • 4
  • 19
  • 26