
回复
作为在鸿蒙开发中处理过海量文本的老开发,曾因字符串编码问题导致国际化应用乱码,也被正则性能坑过。本文结合实战经验,分享仓颉语言字符串处理的核心技巧,帮你避开常见陷阱。
类型 | 定义方式 | 转义规则 | 典型场景 |
---|---|---|---|
单行字符串 | "" 或'' |
支持\n 、\" 等转义 |
短文本、标签 |
多行字符串 | """ 或''' |
保留原始换行 | SQL语句、HTML片段 |
原始字符串 | #"..."# |
不处理转义字符 | 正则表达式、路径字符串 |
// 单行字符串(短文本)
let title = "HarmonyOS"
// 多行字符串(SQL语句)
let sql = """
SELECT * FROM users
WHERE age > 18
"""
// 原始字符串(正则表达式)
let regex = #"\d{4}-\d{2}-\d{2}"# // 匹配日期
let name = "张三"
let age = 28
let info = "用户 \(name) 年龄 \(age) 岁" // "用户 张三 年龄 28 岁"
// 表达式插值
let result = "计算结果: \(10 * 2 + 5)" // "计算结果: 25"
let price = 19.99
let date = Date()
// 数字格式化
let priceStr = "价格: ¥\(price, .fixed(2))" // "价格: ¥19.99"
// 日期格式化
let dateStr = "日期: \(date, .dateTime.short)" // "日期: 2023/10/15"
let user = User(name: "李四", email: "lisi@example.com")
let profile = """
用户信息:
姓名: \(user.name)
邮箱: \(user.email)
"""
let str = "你好,Hello!"
// UTF-8字节遍历
for byte in str.utf8 {
print("\(byte) ") // 输出UTF-8字节序列
}
// UTF-16代码单元遍历
for unit in str.utf16 {
print("\(unit) ") // 输出UTF-16代码单元
}
// 获取Unicode标量
for scalar in str.unicodeScalars {
print("\(scalar.value) ") // 输出Unicode码点
}
// 字符串规范化
let normalized = "Café".normalized(to: .nfkd) // 处理变音符号
// 语言敏感比较
let compareOptions = CompareOptions()
compareOptions.locale = "fr" // 法语比较规则
let result = "Château".compare("Chateau", options: compareOptions)
import std.regex.*
// 匹配邮箱地址
let emailRegex = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
let email = "user@example.com"
if emailRegex.match(email) {
print("有效邮箱")
}
// 匹配手机号(中国)
let phoneRegex = Regex("1[3-9]\\d{9}")
// 提取URL中的域名
let urlRegex = Regex("https?://(\\w+\\.\\w+)/.*")
let url = "https://harmonyos.com/docs"
if let match = urlRegex.match(url) {
let domain = match.group(1) // "harmonyos.com"
}
// 匹配HTML标签
let htmlRegex = Regex("<(\\w+)>(.*?)</\\1>")
let html = "<div>内容</div>"
let matches = htmlRegex.findAll(html)
// 预编译正则(提升多次匹配性能)
let regex = Regex.compile("#\\d+") // 预编译匹配#123形式的标签
// 惰性匹配(避免贪婪匹配)
let lazyRegex = Regex("<div.*?>.*?</div>") // 非贪婪匹配
### 5.2 正则表达式陷阱
1. **贪婪匹配问题**:
2. ```cj
3. // 反例:贪婪匹配导致错误
4. let regex = Regex("<div>.*</div>") // 匹配第一个<div>到最后一个</div>
// 正例:惰性匹配
let regex = Regex("<div>.*?</div>") // 匹配最近的</div>
Regex("pattern").match(item) // 每次都编译
## 六、总结:字符串处理的最佳实践
1. **字面量选择**:短文本用单行,多行文本用三引号,正则用原始字符串
2. 2. **插值技巧**:复杂表达式用括号包裹,格式化用`.fixed`、`.scientific`等修饰符
3. 3. **Unicode处理**:遍历用`unicodeScalars`,国际化用`CompareOptions`
4. 4. **正则优化**:预编译常用正则,用惰性匹配避免性能问题
5.