-3

How to extract the array of string with Integers, Decimals, and Fractions from a sentence? Please find below input and output in iOS Swift.

Input : array of String["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]

Output : ["32.3", "61 1/4", "23 4/5", "5.23"]

rmaddy
  • 314,917
  • 42
  • 532
  • 579
suneel
  • 57
  • 8

2 Answers2

1

Another approach with Regular Expression

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)

The pattern searches for

  • one or more digits
  • followed by a whitespace character or dot
  • followed by one or more digits or slashes
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Add this for supporting regex matches for string:

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

And then:

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)

Source : Swift replace substring regex

Robin Delaporte
  • 575
  • 5
  • 15
  • the string will be any string, it's a dynamic test input, not only width, length, any string. For your case, if it is static data, your extraction is correct. for dynamic data, how to extract the numbers or fractions or digits. – suneel Jul 06 '17 at 06:44
  • Thanks a lot, you saved my time. now it's perfectly working. – suneel Jul 06 '17 at 06:54
  • Consider that each extracted string starts with a (white)space character. – vadian Jul 06 '17 at 07:00