Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to split a string with multiple separators in Swift

2 Answers

0 votes
import Foundation

let input = "abc,defg;hijk|lmnop-qrst_uvwxyz"

// Create the regex pattern to match comma, semicolon, pipe, dash, underscore
let separators = "[,;|\\-_]+"

let regex = try! NSRegularExpression(pattern: separators)
let nsString = input as NSString
let range = NSRange(location: 0, length: nsString.length)

var words: [String] = []
var lastEnd = 0

for match in regex.matches(in: input, range: range) {
    let matchRange = match.range
    let word = nsString.substring(with: NSRange(location: lastEnd, length: matchRange.location - lastEnd))
    words.append(word)
    lastEnd = matchRange.location + matchRange.length
}

if lastEnd < nsString.length {
    words.append(nsString.substring(from: lastEnd))
}

for word in words {
    print(word)
}




/*
run:

abc
defg
hijk
lmnop
qrst
uvwxyz

*/



 



answered Jul 21, 2025 by avibootz
0 votes
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

*/

 



answered Jul 21, 2025 by avibootz
...