当前位置:首页 > 编程技术 > 正文

ios如何提取数字

ios如何提取数字

在iOS开发中,提取字符串中的数字可以通过多种方法实现。以下是一些常见的方法: 1. 使用正则表达式(Regex)使用`NSRegularExpression`类可以很...

在iOS开发中,提取字符串中的数字可以通过多种方法实现。以下是一些常见的方法:

1. 使用正则表达式(Regex)

使用`NSRegularExpression`类可以很方便地提取字符串中的数字。

```swift

import Foundation

let text = "Hello 123, this is a test string with 456 numbers."

let regex = try! NSRegularExpression(pattern: "d+", options: .caseInsensitive)

let nsRange = NSRange(text.startIndex..

let results = regex.matches(in: text, options: [], range: nsRange)

let numbers = results.map { match -> Int in

let matchRange = match.range

let numberString = String(text[matchRange])

return Int(numberString) ?? 0

最新文章