I use Swift.
I want to extract a character string surrounded by specific characters. What should I do?


"hogehoge 【xxx】 abcdefg"

I want to extract the part enclosed by [] ("xxx" in the above example) from a string such as


I would be happy if someone could give me advice.

  • Answer # 1

    You can extract it using regular expressions.

    I have tried it myself, but I think this is good.

    let text = "hogehoge [xxx] abcdefg"
    let nstext = text as NSString
    if let regex = try? NSRegularExpression (pattern: "[(. *?)]"),
        let match = regex.firstMatch (in: text, options: [], range: NSRange (location: 0, length: nstext.length)) {
        print (nstext.substring (with: match.range (at: 1))) // xxx

    Because I've seen an article that doesn't work if I create an NSRange using String.count, I'm using NSString.length (this is a little tricky).

Related articles