如何从句子中提取带有整数,小数和分数的字符串数组? 请在iOS Swift中找到以下输入和输出。
输入:字符串数组["宽度32.3","长度61 1/4","高度23 4/5","措施5.23"]
输出:[" 32.3"," 61 1/4"," 23 4/5"," 5.23"]
答案 0 :(得分:1)
使用正则表达式的另一种方法
let array = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
let pattern = "\\d+[\\s.][\\d/]+"
let regex = try! NSRegularExpression(pattern: pattern)
var result = [String]()
for item in array {
if let match = regex.firstMatch(in: item, range: NSRange(location:0, length: item.characters.count)) {
result.append((item as NSString).substring(with: match.range))
}
}
print(result)
模式搜索
答案 1 :(得分:0)
添加此项以支持字符串的正则表达式匹配:
extension String {
mutating func stringByRemovingRegexMatches(pattern: String, replaceWith: String = "") {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, self.characters.count)
self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return
}
}
}
然后:
var str = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
var vreturn:[String]=[]
for var s in str {
s.stringByRemovingRegexMatches(pattern:"[a-zA-Z]", replaceWith: "")
vreturn.append(s)
}
print( vreturn)