Ignacio Oroná
Ignacio Oroná

Reputation: 4399

Swift regex function update

I have the following function

static func replaceAtSignNotation(_ text : String) -> String {
    var source = text
    let wholePattern = "@\\[[a-z0-9-\\-]+\\]\\((\\w+)\\)"
    let typePattern = "(?<=]\\()[^)]+(?=\\))"

    if let wholeRange = source.range(of: wholePattern, options: .regularExpression) {
        if let typeRange = source.range(of: typePattern, options: .regularExpression) {
            let username = source[typeRange]
            source.replaceSubrange(wholeRange, with: "@\(username)")
        }
    } else {
        return text
    }
    return replaceAtSignNotation(source)
}

which is doing an excellent job finding patterns such as:

@[a12-3asd-32](john) 
@[b12-32d1-23](martha)

And allowing me to catch the username, but some username do contain a '-' such as:

@[c12-12d1-13](john-user-1)

But my current regex is not capturing those cases. Any idea how I can adapt my regex to captuve those cases as well?

Upvotes: 2

Views: 49

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may change the first regex to

let wholePattern = "@\\[[a-z0-9-]+\\]\\((\\w+(?:-\\w+)*)\\)"
                                             ^^^^^^^^^^

See the regex demo.

Or, if the -s can be anywhere and can follow one another, you may also use

let wholePattern = "@\\[[a-z0-9-]+\\]\\(([\\w-]+)\\)"
                                         ^^^^^^^

See another regex demo.

Details

  • @\[ - a literal @[ substring
  • [a-z0-9-]+ - 1+ lowercase ASCII letters, digits or -
  • \]\( - a ]( substring
  • (\w+(?:-\w+)*) - Group 1:
    • \w+ - 1 or more letters, digits or _
    • (?:-\w+)* - zero or more sequences of
      • - - a hyphen
      • \w+ - 1+ word chars
  • [\w-]+ - 1 or more word or - chars
  • \) - a ) char.

Upvotes: 2

Related Questions