-4

What would the regex be (to be used in IOS, "NSRegularExpression") to get the "words" from a string delimited by a space(s), i.e. could be " ", or " ", or " " etc as the delimited.

So therefore:

"26:43:33 S     153:02:51   E"

Would give:

1-"26:43:33"
2-"S"
3-"153:02:51"
4-"E"
Greg
  • 34,042
  • 79
  • 253
  • 454

2 Answers2

2

So therefore:

"26:43:33 S     153:02:51   E"

Would give:

1-"26:43:33"
2-"S"
3-"153:02:51"
4-"E"

So if you're going to use a regex for this, you want to look for all contiguous stretches of not-space. Like this:

let s = "26:43:33 S     153:02:51   E" as NSString
let pattern = "[^ ]+"
let reg = try! NSRegularExpression(pattern: pattern, options: [])
let matches = reg.matchesInString(s as String, options: [], range: NSMakeRange(0, s.length))
let result = matches.map {s.substringWithRange($0.range)}
// result is: ["26:43:33", "S", "153:02:51", "E"]
matt
  • 515,959
  • 87
  • 875
  • 1,141
2

As an alternative to regex, I would suggest using the split method on your string.

let string = "26:43:33 S     153:02:51   E"
let words = string.characters.split { $0 == " " }.map { String($0) }

Because calling split on the characters property will return an array of Character types, we need to use the map method to convert them back to strings. map will perform a closure on each element of a collection. In this case we just use it to cast each element to a String

Slayter
  • 1,172
  • 1
  • 13
  • 26
  • 1
    I agree completely. The use case in the OP's particular question seems an unnecessary use of regex. My answer was intended merely to show how you _would_ do it _if_ you were using regex; in a more complex case, I suppose it might be useful. – matt May 19 '16 at 13:41
  • Does multiple spaces not impact this however? – Greg May 22 '16 at 02:07
  • No they won't have an impact. – Slayter May 22 '16 at 02:57