从你的示例文本开始,我们可以修剪两端:
let sample = " \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n tjhfhdf \n "
let trimmedEnds = sample.trimmingCharacters(in: .whitespacesAndNewlines)
如果您只想删除空格和压缩换行符:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: " ", with: "") // remove all spaces
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression) // squash runs of two or more newlines
或者使用正则表达式来匹配空格:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: " +", with: "", options: .regularExpression)
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)
但是(为了好玩?)所有Unicode水平(空格、制表符等)和垂直(换行符、进纸符、段落分隔符等)的情况怎么办? 对此,有正则表达式模式\h
和\v
:
let noHorizSpace = trimmedEnds.replacingOccurrences(of: "\\h+", with: "", options: .regularExpression)
let singleVertSpace = noHorizSpace.replacingOccurrences(of: "\\v+", with: "\n", options: .regularExpression)
您可以使用单个正则表达式解决此问题,但最好遵循ICU RE用户指南中的建议,使用多个更简单的正则表达式。
let result = title.replacingOccurrences(of: "\n", with: "")
- EmilioPelaez