在 Swift 中删除字符串开头的所有换行符

问题描述:

我有一个这样的字符串:

I have a string like this:

"

BLA
Blub"

现在我想删除所有前导换行符.(但只有第一个真词"出现之前的那些.这怎么可能?

Now I would like to remove all leading line breaks. (But only the ones until the first "real word" appears. How is this possible?

谢谢

如果可以接受从字符串的两端删除换行符(和其他空白)字符,那么您可以使用>

If it is acceptable that newline (and other whitespace) characters are removed from both ends of the string then you can use

let string = "\n\nBLA\nblub"
let trimmed = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// In Swift 1.2 (Xcode 6.3):
let trimmed = (string as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

要删除前导换行符/空白字符,只有您可以(例如)使用正则表达式搜索并替换:

To remove leading newline/whitespace characters only you can (for example) use a regular expression search and replace:

let trimmed = string.stringByReplacingOccurrencesOfString("^\\s*",
    withString: "", options: .RegularExpressionSearch)

"^\\s*" 匹配字符串开头的所有空格.使用 "^\\n*" 仅匹配换行符.

"^\\s*" matches all whitespace at the beginning of the string. Use "^\\n*" to match newline characters only.

Swift 3 (Xcode 8) 的更新:

let trimmed = string.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)