0

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)
}
1
  • 1
    To make sure you only match the GUID in brackets and then the username use "(?<=@\\[[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{8}\\]\\()[^()]+" Commented Jun 26, 2018 at 17:00

1 Answer 1

1

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 )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.