2

In Perl if I had trailing blanks in a string, I would use this code

$line =~ s/ +$//;

Is there a similar command or function in swift?

2 Answers2

2

Swift provides no support for regular expressions. It doesn't need to, though, because the only place you'll ever use Swift is in the presence of Cocoa — and Cocoa's Foundation framework does provide support for regular expressions (and has other string-handling commands). Swift String and Framework's NSString are bridged to one another.

Thus, you could use stringByReplacingOccurrencesOfString:withString:options:range: with a regular expression pattern, for example (assuming that stringByTrimmingCharactersInSet: is too simple-minded for your purposes).

matt
  • 515,959
  • 87
  • 875
  • 1,141
2

If you want to do this multiple times I suggest you add this handy extension to your project:

extension String {
    var strip: String {
        return self.trimmingCharacters(in: .whitespaces)
    }
}

Now you can do something as simple as this:

let line = " \t BB-8 likes Rey \t "
line.strip // => "BB-8 likes Rey"

If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the example above:

import HandySwift    

let line = "  BB-8 likes Rey  "
line.strip // => "BB-8 likes Rey"
Jeehut
  • 20,202
  • 8
  • 59
  • 80