How to replace multiple consecutive question marks (?) with a single question mark in Swift

1 Answer

0 votes
import Foundation

let str = "What??? Why?? How?????"

// Create regex pattern to match one or more '?'
let pattern = "\\?+"

do {
    let regex = try NSRegularExpression(pattern: pattern)
    let range = NSRange(location: 0, length: str.utf16.count)

    // Replace all matches with a single '?'
    let result = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "?")
    
    print(result)
} catch {
    print("Invalid regex pattern")
}



/*
run:

What? Why? How?

*/

 



answered Jul 24, 2025 by avibootz
...