【问题标题】:Find number in string and return location and length在字符串中查找数字并返回位置和长度
【发布时间】:2019-01-05 17:58:33
【问题描述】:
let myStr = "I have 4.34 apples."

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

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

【问题讨论】:

    标签: swift numbers find return location


    【解决方案1】:

    我的建议也是基于正则表达式,但是有一种更方便的方法可以从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+)?"
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多