首页 > 解决方案 > 如何在 Swift 中验证类似这样的字符串(例如:27˚)。值是随机的?

问题描述

正如我们所知,用 swift (\u{00B0}) 表示 ˚ 是值。但这里需要一个正则表达式来验证像 27˚ 或 15˚ 这样的数据。如何快速实现?

标签: regexxcodeswift5

解决方案


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

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)
}

推荐阅读