You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何从长文本提取带@的完整姓名组合?

问题

给定字符串:"Hello @User Name and hello again @Full Name and this works"
期望输出:["@User Name", "@Full Name"]

现有代码

let commentString = "Hello @User Name and hello again @Full Name and this works"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "@"

for word in words.filter({ $0.hasPrefix(mentionQuery) }) {
    print(word) // 输出 "@User" 和 "@Full"
}

尝试代码

if words.filter({ $0.hasPrefix(mentionQuery) }).isNotEmpty {
    print(words) // 输出 ["Hello", "@User", "Name".. etc.]
}

目前无法获取包含完整姓名的字符串数组["@User Name", "@Full Name"],请求解决方法。

解决方法

通过空格分割字符串的方式会把带空格的姓名拆分成独立单词,无法保留完整格式,推荐用正则表达式来匹配完整的带空格用户名。

实现代码

import Foundation

let commentString = "Hello @User Name and hello again @Full Name and this works"
// 匹配@开头、由首字母大写的多单词组成的姓名
let pattern = "@[A-Z][a-z]+( [A-Z][a-z]+)*"

do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    let matches = regex.matches(
        in: commentString,
        options: [],
        range: NSRange(location: 0, length: commentString.utf16.count)
    )
    
    let mentions = matches.compactMap { match -> String? in
        guard let range = Range(match.range, in: commentString) else { return nil }
        return String(commentString[range])
    }
    
    print(mentions) // 输出 ["@User Name", "@Full Name"]
} catch {
    print("正则表达式错误: \(error.localizedDescription)")
}

代码说明

  • 正则表达式@[A-Z][a-z]+( [A-Z][a-z]+)*的规则:
    • @:匹配开头的@符号
    • [A-Z][a-z]+:匹配首字母大写、后续为小写字母的单个单词(如User、Name)
    • ( [A-Z][a-z]+)*:匹配0个或多个「空格+同格式单词」的组合,支持多单词姓名
  • 利用NSRegularExpression查找所有匹配项,转换为字符串数组后即可得到完整的用户名列表。

如果用户名包含其他格式(如数字、全大写字母),可调整正则表达式的字符范围,比如将[A-Z][a-z]+改为[A-Za-z0-9]+来兼容更多字符。

内容的提问来源于stack exchange,提问作者Scott W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:40:29