import Foundation
/// Splits a string using multiple separators: comma, semicolon, pipe, dash, underscore
func splitBySeparators(input: String, separators: String) -> [String] {
let regex = try! NSRegularExpression(pattern: separators)
let nsString = input as NSString
let matches = regex.split(input: nsString)
return matches
}
extension NSRegularExpression {
/// Helper to split a string using the regex
func split(input: NSString) -> [String] {
let range = NSRange(location: 0, length: input.length)
var results: [String] = []
var lastEnd = 0
for match in self.matches(in: input as String, range: range) {
let matchRange = match.range
let word = input.substring(with: NSRange(location: lastEnd, length: matchRange.location - lastEnd))
results.append(word)
lastEnd = matchRange.location + matchRange.length
}
if lastEnd < input.length {
results.append(input.substring(from: lastEnd))
}
return results
}
}
let input = "abc,defg;hijk|lmnop-qrst_uvwxyz"
let separators = "[,;|\\-_]+"
let words = splitBySeparators(input: input, separators: separators)
for word in words {
print(word)
}
/*
run:
abc
defg
hijk
lmnop
qrst
uvwxyz
*/