ios - 删除字符串开头的非字母字符
问题描述
我想替换字符串的所有非字母数字字符(包括空格),直到第一个字母
"\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”。我们怎么能只替换起始字符?
解决方案
我可以使用正则表达式删除前导空格。这是代码:
extension String {
func trimLeadingWhitespaces() -> String {
return self.replacingOccurrences(of: "^\\s+", with: "", options: .regularExpression)
}
}
let string = " Some string abc"
let trimmed = string.trimLeadingWhitespaces()
print(trimmed)
推荐阅读
- java - Java 类对象分配的值在其他线程中可用,而我不希望这样
- javascript - 将 django 变量传递给 javascript
- javascript - axios通过post发送图片
- snort - windows环境下如何在snort中配置速率过滤器?
- android - 如何更新固定的ssl证书android
- reactjs - 如何正确地为 id 和 new 制作路线?
- google-chrome-extension - 用于阅读 gmail 附件内容的 chrome 扩展 (pdf)
- jenkins-pipeline - ElasTest Jenkins 插件不发送测试日志
- webpack - Webpack 编译很慢
- arrays - 当字符小于 255 时 VBA FormulaArray 范围类错误