Search code examples
swiftnumbersfindreturnlocation

Find number in string and return location and length


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
    }
}

Solution

  • 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.