Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove substring from a string knowing first and last characters in Swift

Tags:

string

swift

Having a string like this:

let str = "In 1273, however, they lost their son in an accident;[2] the young Theobald was dropped by his nurse over the castle battlements.[3]"

I'm looking for a solution of removing all appearances of square brackets and anything that between it.

I was trying using a String's method: replacingOccurrences(of:with:), but it requires the exact substring it needs to be removed, so it doesn't work for me.

like image 545
bohdankoshyrets Avatar asked Jan 05 '23 02:01

bohdankoshyrets


1 Answers

You can use:

let updated = str.replacingOccurrences(of: "\\[[^\\]]+\\]", with: "", options: .regularExpression)

The regular expression (without the required escapes needed in a Swift string is:

\[[^\]+]\]

The \[ and \] look for the characters [ and ]. They have a backslash to remove the normal special meaning of those characters in a regular expression.

The [^]] means to match any character except the ] character. The + means match 1 or more.

like image 75
rmaddy Avatar answered Jan 16 '23 17:01

rmaddy