如何验证 Swift.The 值中类似这样的字符串(例如:27˚)是随机的?

How to verify string something like this (For eg: 27˚) in Swift.The value is random?

我们知道在swift(\u{00B0})中代表˚就是这个值。但这里需要一个正则表达式来验证 27˚ 或 15˚ 等数据。如何在swift中实现?

你可以像这样直接在正则表达式中使用它

let str = "37 Hello World 37\u{00B0}"
let range = NSRange(location: 0, length: str.utf16.count)
let regex = try! NSRegularExpression(pattern: "[0-9]+\u{00B0}")
let match = regex.firstMatch(in: str, options: [], range: range)
print(match?.range)
Optional({15, 3})

如果你想同时匹配\u{00B0}˚,你可以在正则表达式中写(\u{00B0}|˚)

let str = "37 Hello World 37\u{00B0} 37˚"
let range = NSRange(location: 0, length: str.utf16.count)
let regex = try! NSRegularExpression(pattern: "[0-9]+(\u{00B0}|˚)")

let matches = regex.matches(in: str, options: [], range: range)

for match in matches {
    print(match.range)
}