Home > Software design >  How to remove all values within square brackets, including the brackets | Swift
How to remove all values within square brackets, including the brackets | Swift

Time:08-03

Looking to remove everything within a strings square brackets, including the square brackets. How can this be done in Swift? The Values in the square brackets can vary.

Sample String:

[2049A30-3930Q4] The Rest of the String

Desired Result:

The Rest of the String

CodePudding user response:

You can use the String split function:

let sampleString = "[2049A30-3930Q4] The Rest of the String"
let preSplit = sampleString.replacingOccurrences(of: "] ", with: "]")
if let results = preSplit.split(separator: "]").last {
    print(results)
}

CodePudding user response:

you could try something simple like this:

var sampleString = "[2049A30-3930Q4] The Rest of the String"

sampleString.removeSubrange(sampleString.startIndex..."[2049A30-3930Q4]".endIndex)
// this will also work
// sampleString.removeSubrange(sampleString.startIndex..."[0000000-000000]".endIndex)
print("----> sampleString: \(sampleString)")

  

EDIT-1: more general approach if needed.

if let from = sampleString.range(of: "[")?.lowerBound,
   let to = sampleString.range(of: "]")?.upperBound {
    sampleString.removeSubrange(from...to)
    print("----> sampleString: \(sampleString)")
}
  • Related