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?

6

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, this will work. stringByReplacingOccurrencesOfString:withString:options:range:
Matt alludes to a better answer for this specific case which is stringByTrimmingCharactersInSet:
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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.