regex - 如何在 Swift 中验证类似这样的字符串(例如:27˚)。值是随机的?
问题描述
正如我们所知,用 swift (\u{00B0}) 表示 ˚ 是值。但这里需要一个正则表达式来验证像 27˚ 或 15˚ 这样的数据。如何快速实现?
解决方案
你可以像这样在正则表达式中直接使用它
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)
}
推荐阅读
- r - 使用二元组创建共现矩阵
- java - 从 android 设备向 android things 发送命令
- ruby-on-rails - ActiveAdmin 中的自定义页面
- angular - mergeMap 函数在 Angular 5 中出错
- unity3d - unity 3rd 人称控制器,旋转噩梦
- java - 如何在 java 中读取 JSON-LD?
- c++ - 在我自己的堆栈中实现顶部的问题
- pyspark - Dataproc:pyspark UDF 的 functools.partial 没有属性“__module__”错误
- java - 如何将带有用户名和密码的 Java mqtt 客户端连接到 emqttd(EMQ) 代理?
- objective-c - 如何排除类
-swift.h