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

如何将语句中的指定单词定义为变量?Swift UITextField场景实现

解决Swift中提取输入文本里的名字到变量的问题

嘿,我来帮你搞定这个需求!你想要从输入的文本(格式类似my name is 张三)里提取出名字部分,赋值给enteredName变量对吧?咱们来调整你的代码,实现这个功能:

方案1:简单前缀匹配(适合固定格式输入)

这种方法直接检查输入是否以指定前缀开头,然后提取后面的内容,简单易理解:

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    performAction() 
    return true 
} 

// 假设textField是你的类属性,确保performAction能访问到它
var textField: UITextField!

func performAction() { 
    // 先获取输入文本,同时去掉前后的空格和换行,避免无效输入
    guard let entry = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) else {
        print("请输入有效的内容")
        return
    }
    
    let namePrefix = "my name is "
    // 检查输入是否符合前缀格式
    if entry.hasPrefix(namePrefix) {
        // 去掉前缀部分,得到名字
        let enteredName = entry.dropFirst(namePrefix.count).trimmingCharacters(in: .whitespaces)
        
        // 确保名字不为空
        if !enteredName.isEmpty {
            print("Your name is \(enteredName).")
        } else {
            print("请在'my name is'后面输入你的名字哦")
        }
    } else {
        print("请按照'my name is [你的名字]'的格式输入")
    }
}

代码说明:

  • trimmingCharacters(in: .whitespacesAndNewlines):处理用户输入前后的多余空格或换行,提升鲁棒性
  • hasPrefix(namePrefix):快速判断输入是否符合预期格式
  • dropFirst(namePrefix.count):精准去掉前缀字符串,提取后面的名字内容
  • 额外增加了空名字的判断,避免用户只输入my name is 的情况

方案2:正则表达式(支持更灵活的输入格式)

如果需要支持大小写不敏感(比如用户输入My Name Is Alice),或者名字包含空格(比如my name is John Doe),可以用正则表达式来实现:

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    performAction() 
    return true 
} 

var textField: UITextField!

func performAction() { 
    guard let entry = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) else {
        print("请输入有效的内容")
        return
    }
    
    // 正则规则:匹配以"my name is"开头,后面跟着至少一个空格,再后面是任意字符(直到结尾),忽略大小写
    let regexPattern = "^my name is\\s+(.+)$"
    guard let regex = try? NSRegularExpression(pattern: regexPattern, options: .caseInsensitive) else {
        print("正则初始化失败")
        return
    }
    
    let fullRange = NSRange(entry.startIndex..., in: entry)
    // 查找第一个匹配项
    if let matchResult = regex.firstMatch(in: entry, options: [], range: fullRange) {
        // 提取第一个捕获组的内容(也就是名字部分)
        if let nameRange = Range(matchResult.range(at: 1), in: entry) {
            let enteredName = String(entry[nameRange])
            print("Your name is \(enteredName).")
        }
    } else {
        print("请按照'my name is [你的名字]'的格式输入(大小写不限制)")
    }
}

代码说明:

  • NSRegularExpression的.caseInsensitive选项:让匹配不区分大小写
  • 正则中的(.+):捕获前缀之后的所有内容,支持名字包含空格的情况
  • 通过range(at:1)获取捕获组的内容,也就是我们需要的名字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:44:09