Created
November 4, 2023 11:42
-
-
Save calvingit/85e6b1cad6dc9b0499f328b8847d2778 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
// 移除空白 | |
func removingWhitespace() -> String { | |
let whitespacePattern = "\\s+" | |
let regex = try? NSRegularExpression(pattern: whitespacePattern, options: .caseInsensitive) | |
let range = NSRange(location: 0, length: count) | |
return regex?.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "") ?? self | |
} | |
// 移除emoji | |
func removingEmojis() -> String { | |
let emojiPattern = "[\\u{1F600}-\\u{1F64F}\\u{1F300}-\\u{1F5FF}\\u{1F680}-\\u{1F6FF}\\u{1F1E0}-\\u{1F1FF}\\u{2600}-\\u{26FF}\\u{2700}-\\u{27BF}\\u{1F900}-\\u{1F9FF}\\u{1F018}\\u{1F3F0}\\u{1F3FB}-\\u{1F3FF}\\u{1F9B0}-\\u{1F9B3}\\u{1F9E6}]" | |
let regex = try? NSRegularExpression(pattern: emojiPattern, options: .caseInsensitive) | |
let range = NSRange(location: 0, length: count) | |
return regex?.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "") ?? self | |
} | |
/// 计算字节数,中文算非ASCII字符,占2个字节 | |
func lengthInBytes() -> Int { | |
var length = 0 | |
for char in self { | |
if char.isASCII { | |
length += 1 | |
} else { | |
length += 2 | |
} | |
} | |
return length | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment