I have a string "323 ECO Economics Course 451 ENG English Course 789 Mathematical Topography"
I want to split this string using the regex expression [0-9][0-9][0-9][A-Z][A-Z][A-Z]
so that the function returns the array:
Array =
["323 ECO Economics Course ", "451 ENG English Course", "789 Mathematical Topography"]
How would I go about doing this using swift?
Edit
My question is different than the one linked to. I realize that you can split a string in swift using myString.components(separatedBy: "splitting string")
The issue is that that question doesn't address how to make the splitting string
a regex expression. I tried using mystring.components(separatedBy: "[0-9][0-9][0-9][A-Z][A-Z][A-Z]", options: .regularExpression)
but that didn't work.
How can I make the separatedBy:
portion a regular expression?
You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
You can use regex "\\b[0-9]{1,}[a-zA-Z ]{1,}"
and this extension from this answer to get all ranges of a string using literal, caseInsensitive or regularExpression search:
extension StringProtocol {
func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...].range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
let inputString = "323 ECO Economics Course 451 ENG English Course 789 Mathematical Topography"
let courses = inputString.ranges(of: "\\b[0-9]{1,}[a-zA-Z ]{1,}", options: .regularExpression).map { inputString[$0].trimmingCharacters(in: .whitespaces) }
print(courses) // ["323 ECO Economics Course", "451 ENG English Course", "789 Mathematical Topography"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With