在Swift中使用正则表达式来查找字符串的子字符串

时间:2017-09-03 16:24:02

标签: ios regex swift

我使用以下代码在Swift中使用regex查找子字符串:

    let searchString = "Please contact us at <a href=\"tel:8882223434\" ><font color=\"#003871\"><b> 888.222.3434 </b></font></a> for assistance"
    let regexp = "^\\d+(\\.\\d+)*$"
    if let range = searchString.range(of:regexp, options: .regularExpression) {
        let result = searchString.substring(with:range)
        print(result) // <---- not printing the resulting string
    }

所需的输出为888.222.3434

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

删除锚点并将*替换为+

let regexp = "\\d+(\\.\\d+)+"

<强>详情

  • \d+ - 一位或多位
  • (\\.\\d+)+ - 一个或多个序列:
    • \. - 一个点
    • \d+ - 一位或多位数。
相关问题