我正在做一個專案,在該專案中,我得到了一個用戶和他們的生日,以及該人去過的電影和日期的串列。一個示例字串是這樣的:"Participant Name: Example name, Birthdate: 01/11/2000, Spiderman 05/15/2021 07/16/2021 08/17/2021 Avengers Infinity War 05/15/2020 07/16/2020 08/17/2020 The Lorax 01/05/2015"等等。我知道該字串將包含哪些電影,并且我知道每部電影的最大日期數量,但我不知道該人會看這部電影的具體次數。我已經為生日做了以下事情,這只是因為請求的格式總是以生日的方式相同:
func FindBirthdate(str: String) -> Date{
//I make sure that the text before birthdate is always converted to DOB
//in other functions, and that the string is converted
//to an array seperated by spaces.
let index = str.firstIndex(of: "DOB:")!
let birthdate = str[index 1]
print(birthdate)
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
formatter.locale = Locale(identifier: "COUNTRY IDENTIFIER")
formatter.timeZone = TimeZone(identifier: "EXAMPLE")
return formatter.date(from: birthdate) ?? Date()
}
但是,正如我之前所說,我不知道用戶會看多少次電影。所有電影都將按相同的順序排列。我如何將每部電影之間的角色拆分為該電影的日期?再一次,我的問題是我不知道日期的數量,那么我將如何獲取每個日期并回傳一個串列?我研究了一種ForEach statement,但我不確定如何將它整合到一個字串中。這個答案建議我使用正則運算式,但是,這僅關注日期,而不是電影。該字串不僅僅由日期組成。我還查看了 Swift 中的示例日期決議,但這只是單個日期。我的問題不是日期轉換,而是 s 首先查找和分隔日期。上Meta也有人建議我嘗試拆分。我看過 Apple Developer 上的拆分,這似乎是一個很好的解決方案,但我不確定我會用什么拆分。要再次顯示該示例字串,"Participant Name: Example name, Birthdate: 01/11/2000, Spiderman 05/15/2021 07/16/2021 08/17/2021 Avengers Infinity War 05/15/2020 07/16/2020 08/17/2020 The Lorax 01/05/2015". 電影名稱將永遠只有這些——它們永遠不會有數字。日期也將始終采用相同的 MM/DD/YYYY 格式。名稱緊接在日期之前,除了空格之外沒有分隔符。
之前沒有問過這個問題的原因是,雖然其他問題可能會詢問有關日期決議或查找子字串的問題,但我需要找到每部電影和電影標題的每個單獨日期 - 這是試圖在每部電影的字串。
uj5u.com熱心網友回復:
這對你有用嗎?我假設您完全遵循示例中的文本格式。
extension String {
func match(_ regex: String) -> [[String]] {
let nsString = self as NSString
return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)).map { match in
(0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
} ?? []
}
}
然后:
func getName(text: String) -> String? {
guard let match = text.match("(?<=Participant Name: )(.*)(?=, Birthdate)").first else { return nil }
return match.first
}
func getBirthDay(text: String) -> String? {
guard let match = text.match("(?<=Birthdate: )(.*)(?=, )").first else { return nil }
return match.first
}
func getMovies(text: String) -> [String: [String]] {
var result: [String: [String]] = [:]
guard let moviesString = text.match("(?<=Participant Name: \(getName(text: text)!), Birthdate: \(getBirthDay(text: text)!), )(.*)").first?.first else { return result }
let asArray = moviesString.components(separatedBy: " ")
var key: String = ""
var values = [String]()
var lastKey: String = ""
for item in asArray {
if !isDate(item) {
values.removeAll()
key = key != "" ? (" " item) : item
lastKey = key
continue
} else {
key = ""
if var existingValues = result[lastKey] {
existingValues.append(item)
result[lastKey] = existingValues
} else {
result[lastKey] = [item]
}
}
}
return result
}
func isDate(_ string: String) -> Bool {
return !string.match("[0-9]{2}(/)[0-9]{2}(/)[0-9]{4}").isEmpty
}
去測驗:
let text = "Participant Name: Example name, Birthdate: 01/11/2000, Spiderman 05/15/2021 07/16/2021 08/17/2021 Avengers Infinity War 05/15/2020 07/16/2020 08/17/2020 The Lorax 01/05/2015"
let movies = getMovies(text: text)
print(">>>> \(movies["Spiderman"])")
輸出:
Optional(["05/15/2021", "07/16/2021", "08/17/2021"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484075.html
上一篇:如何使今天的日期等于特定日期?
