Wallace
Wallace

Reputation: 23

Using regex in Swift to find a substring of a string

I'm using the following code to find a substring using regex in Swift:

    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
    }

The desired output is 888.222.3434

Any help would be greatly appreciated. Thank you.

Upvotes: 2

Views: 2422

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

Remove the anchors and replace * with +.

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

Details

  • \d+ - 1 or more digits
  • (\\.\\d+)+ - one or more sequences of:
    • \. - a dot
    • \d+ - 1 or more digits.

Upvotes: 2

Related Questions