-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
  • 307,833
  • 40
  • 508
  • 550
Bogdan Bogdanov
  • 1,182
  • 11
  • 35
  • 72

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
  • 253,546
  • 28
  • 306
  • 323