我有一个字符串为"12:66 PM".现在我想用60替换字符串66.所以我想检查":"之后是否应该用60或任何值替换两个字符.
请建议
您可以使用regexp-search-and-replace:
string.replacingOccurrences(of: "regexp", with: "replacement", options: .regularExpression)
所以,在你的情况下:
var time = "12:66 PM" time.replacingOccurrences(of: ":\\d\\d", with: ":60", options: .regularExpression) // > "12:60 PM"
将其抽象为函数是直截了当的:
func replaceMinutes(in time: String, with minutes: String) -> String { return time.replacingOccurrences(of: ":\\d\\d", with: ":\(minutes)", options: .regularExpression) }
如有必要,您可能需要检查输入字符串是否符合您的预期:
nil != time.range(of: "^\\d\\d:\\d\\d [AP]M$", options: .regularExpression) && nil != minutes.range(of: "^\\d\\d$", options: .regularExpression)
如果您无法理解其中的任何方法,我建议您阅读a)Swift语言的基础知识和b)正则表达式.