Swift: substring (integer/number) from a string

  • A+
Category:Languages

I'm working on a Speech Recogniser module in my app. Speech recogniser return a string (may be some time with garbage string information, closely matching with user's speech) and I have to evaluate specific command from a string.

Here are some speech result string examples, that I'm getting:

  • "open case"
  • "open case 1234"
  • "open case id 3421"
  • "open case no 9546"
  • "open case number 5241"
  • "open case 9552 open case"
  • "open case open case 6842"
  • "open case bla bla 5415 bla"
  • "open case 1234 bla bla"
  • "open case number 54675 bla bla 1234 bla" . // first integer should be considered in command

Now, I've a set of command list, one of command is open case <Integer value>

I could easily evaluate a word open case using substring utility functions of Swift. But the problem is, I've to find out (identify and get) an integer number from a speech string after keyword open case.

I've looked around following answer but couldn't find exact result/solution:


I recommend Regular Expression.

The pattern searches for

  • Literal "open case",
  • An optional whitespace character (//s?)
  • One or more digits. (//d+) which is captured

The code evaluates all examples:

let array = ["open case", "open case 1234", "open case id 3421", "open case no 9546", "open case number 5241", "open case 9552 open case", "open case open case 6842", "open case bla bla 5415 bla", "open case 1234 bla bla", "open case number 54675 bla bla bla"]  func evaluate(string : String) -> String? {     let pattern = "open case//s?(//d+)"     let regex = try! NSRegularExpression(pattern: pattern) // as the pattern is hard-coded try! is safe     if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) {         let range = Range(match.range(at: 1), in: string)!         return String(string[range])     }     return nil }  let found = array.compactMap { evaluate(string: $0) } // ["1234", "9552", "6842", "1234"] 

If you want to consider (actually ignore) everything between open case and the integer use the pattern

"open case//D+(//d+)" 

//D+ represents one or more non-digit characters.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: