-2
let myStr = "I have 4.34 apples."

I need the location range and the length, because I'm using NSRange(location:, length:) to bold the number 4.34

extension String{
    func findNumbersAndBoldThem()->NSAttributedString{
         //the code
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79

1 Answers1

1

My suggestion is also based on regular expression but there is a more convenient way to get NSRange from Range<String.Index>

let myStr = "I have 4.34 apples."
if let range = myStr.range(of: "\\d+\\.\\d+", options: .regularExpression) {
    let nsRange = NSRange(range, in: myStr)
    print(nsRange)
}

If you want to detect integer and floating point values use the pattern

"\\d+(\\.\\d+)?"

The parentheses and the trailing question mark indicate that the decimal point and the fractional digits are optional.

vadian
  • 274,689
  • 30
  • 353
  • 361