title: Change text of an attributed string and retain attributes in Swift
body: <p>For output in a database program, I have certain text that I've inserted marks to indicate bold or italics, as well as some text that is substituted for images. For instance:</p>
  
  <p>"%Important% ^All employees to the breakroom^" should have final output as:</p>
  
  <p><strong>Important</strong> <em>All employees to the breakroom</em></p>
  
  <p>I have code written to find the text with "%" signs around it and "^" signs, but the trouble I have now is the text outputs like:</p>
  
  <p><strong>%Important%</strong> ^<em>All employees to the breakroom</em>^</p>
  
  <p>I'd like to remove these % and ^'s while retaining the string's formatting.</p>
  
  <p>This is the code I'm using up until it breaks:</p>
  
  <pre><code>func processText(inString string: String) -&gt; NSAttributedString {
  
  let pattern = ["(?&lt;=\\^).*?(?=\\^)","(?&lt;=\\%).*?(?=\\%)","\\^", "\\%"]
  let italicsRegex = NSRegularExpression(pattern: pattern[0], options: .allZeros, error: nil)
  let range = NSMakeRange(0, count(string))
  let italicsMatches = italicsRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
  
  var attributedText = NSMutableAttributedString(string: string)
  
  for match in italicsMatches! {
      attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Oblique", size: 14.0)!, range: match.range)
  }
  
  let boldRegex = NSRegularExpression(pattern: pattern[1], options: .allZeros, error: nil)
  let boldMatches = boldRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
  
  for match in boldMatches!   {
      attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 14.0)!, range: match.range)
  }
  
  let removeItalicsMarksRegex = NSRegularExpression(pattern: pattern[2], options: .allZeros, error: nil)
  let removeItalicsMarksMatches = removeItalicsMarksRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
  
  var numberOfLoops = 0
  for match in removeItalicsMarksMatches! {
  
      attributedText.replaceCharactersInRange(match.range, withString: "")
  
  }
  
  return attributedText.copy() as! NSAttributedString
  }
  </code></pre>
  
  <p>This works for the % match (but only the first character) and causes a crash on the ^ character immediately.</p>
  
  <p>Any help or advice with resolving this would be appreciated. Thanks.</p>