Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从字符串的句子中提取整数、小数和小数_Ios_Arrays_Swift_String - Fatal编程技术网

Ios 从字符串的句子中提取整数、小数和小数

Ios 从字符串的句子中提取整数、小数和小数,ios,arrays,swift,string,Ios,Arrays,Swift,String,如何从句子中提取包含整数、小数和分数的字符串数组? 请在iOS Swift中找到以下输入和输出 输入:字符串数组[“宽度32.3”,“长度61 1/4”,“高度23 4/5”,“测量值5.23”] 输出:[“32.3”、“61 1/4”、“23 4/5”、“5.23”]添加此项以支持字符串的正则表达式匹配: extension String { mutating func stringByRemovingRegexMatches(pattern: String, replaceWith:

如何从句子中提取包含整数、小数和分数的字符串数组? 请在iOS Swift中找到以下输入和输出

输入:字符串数组[“宽度32.3”,“长度61 1/4”,“高度23 4/5”,“测量值5.23”]


输出:[“32.3”、“61 1/4”、“23 4/5”、“5.23”]

添加此项以支持字符串的正则表达式匹配:

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)

来源:

正则表达式的另一种方法

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)
该模式搜索

  • 一个或多个数字
  • 后跟空白字符或点
  • 后跟一个或多个数字或斜杠

字符串将是任意字符串,它是动态测试输入,而不仅仅是宽度、长度和任意字符串。对于您的情况,如果是静态数据,则您的提取是正确的。对于动态数据,如何提取数字、分数或数字。非常感谢,您节省了我的时间。现在它是完美的。考虑每一个提取的字符串从一个(白色)的空间字符开始。谢谢,这也完全符合我所需要的精确输出。