首页 > 解决方案 > 删除字符串开头的非字母字符

问题描述

我想替换字符串的所有非字母数字字符(包括空格),直到第一个字母

"\r\n                A Simple PDF File \r\n                   This is a small demonstration .pdf file - \r\n                   just for use in the Virtual Mechanics tutorials. More text. And more \r\n                   text."

我用了

 let string = txtView.text
 let newString = string.replacingOccurrences(of: "\n", with: "")

但它替换了字符串的所有“\n”。我们怎么能只替换起始字符?

标签: iosswiftstring

解决方案


我可以使用正则表达式删除前导空格。这是代码:

extension String {
    func trimLeadingWhitespaces() -> String {
        return self.replacingOccurrences(of: "^\\s+", with: "", options: .regularExpression)
    }
}

let string = "       Some string     abc"
let trimmed = string.trimLeadingWhitespaces()
print(trimmed)


推荐阅读