1

I have a attributed string with $ sign like this " price 1 $ 25 \n price 2 $\n price 3 $" I want find all the ranges of "$"

let attrString = NSMutableAttributedString(string: " price 1 $ 25 \n price 2 $\n price 3 $")
let ranges = // all ranges for $ sign

I need to set different color for "$".

I know how to find range in attributed string.

extension NSAttributedString {
func rangeOf(string: String) -> Range<String.Index>? {
    return self.string.range(of: string)
}}

I am wondering how I can find an array of ranges of "$" sign in a given attributed string?

2
  • This may help: stackoverflow.com/questions/36865443/… Commented Dec 5, 2017 at 10:51
  • It may be a better idea to use NSRegularExpression than using String/NSString here :0 Commented Dec 5, 2017 at 10:58

1 Answer 1

1

Quite easy with a roundtrip to AttributedString:

let attrString = NSMutableAttributedString(string: " price 1 $ 25 \n price 2 $\n price 3 $")

let attributedString = AttributedString(attrString)
let substring = "$"

// Iterating through all the occurrences of `substring`.
for range in attributedString.characters.ranges(of: substring) {
   // Do something with the current range
   attributedString[range].foregroundColor = .red
}

let response = NSAttributedString(attributedString)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.