在字符串中查找数字和 return 位置和长度

Find number in string and return location and length

let myStr = "I have 4.34 apples."

我需要位置范围和长度,因为我正在使用 NSRange(location:, length:) 来加粗数字 4.34

extension String{
    func findNumbersAndBoldThem()->NSAttributedString{
         //the code
    }
}

我的建议也是基于正则表达式,但有一种更方便的方法可以从 Range<String.Index>

获取 NSRange
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)
}

如果要检测整数和浮点值,请使用模式

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

括号和结尾的问号表示小数点和小数位是可选的。