Ignacio Oroná
Ignacio Oroná

Reputation: 4399

Swift regex configuration

I am getting strings like "hello @[dbe9234d-9e59-94b01-42342c9sd](user_name) how are you?". I would like to use a regex to extract the 'user_name' part of the regular expression. I am using the following regex, which is returning the whole expression (and I only need the user_name) part. Any ideas?

let source = "hello @[dbe9234d-9e59-94b01-42342c9sd](user_name) how are you?"
typePattern = "@\\[[a-z0-9-\\-]+\\]\\((\\w+)\\)"

if let typeRange = source.range(of: typePattern,
                                options: .regularExpression) {
    print("First type: \(source[typeRange])")
// First type: @[dbe9234d-9e59-94b01-42342c9sd](user_name)
}

Upvotes: 0

Views: 51

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

With your current regex @\[[a-z0-9-\-]+\]\((\w+)\) the username is in the first capturing group (\\w+).

I think you can update the character class to [a-z0-9-]) using a single hyphen.

If you don't want to use the capturing group and your regex engine supports lookbehind (?<= then you could match:

(?<=]\()[^)]+(?=\))

typePattern = "(?<=]\\()[^)]+(?=\\))"

This asserts that what is on the left side is a closing bracket and an opening parenthesis (?<=]\() and then matches not an opening parenthesis using a negated character class [^)]+ and uses a positive lookahead to assert that what follows is a )

Upvotes: 1

Related Questions