Alex
Alex

Reputation: 5278

Regex pattern not inclusive of first character

I'm using this regex pattern: @[a-zA-Z0-9-_]+ to match @usernames in strings.

Hey @alex, whatsup
@brian @mary cool photo

The text highlighted in grey is what is returned by the regex pattern, but I want it to return everything after the @ character. So what I actually want returned is:

Hey @alex, whatsup
@brian @mary cool photo

How should I change the pattern?

Upvotes: 1

Views: 1412

Answers (2)

Code Different
Code Different

Reputation: 93171

Why not just use a capture group? Place round brackets over the alpha-numeric characters after the @. Your match still include the @ sign but you only capture the username:

let str = "Hey @alex, whatsup. @brian @mary cool photo"
let len = count(str) // if Swift 2.0 use: str.characters.count

let regex = NSRegularExpression(pattern: "@([a-zA-Z0-9-_]+)", options: nil, error:nil)
let matches = regex!.matchesInString(str, options: nil, range: NSMakeRange(0,len))
let nStr = str as NSString

for m in matches {
    let r = m.rangeAtIndex(1)
    println(nStr.substringWithRange(r)) // Use print in Swift 2.0
}

I don't have a Swift 2.0 compiler handy so make some changes if you are using Xcode 7 beta

Upvotes: 2

senshin
senshin

Reputation: 10360

You should use a positive lookbehind, which entails asserting the following: I want to match [a-zA-Z0-9-_]+, but only when there is ("positive") an @ before it (hence, "lookbehind").

I don't know Swift regex syntax specifically, but most engines use (?<=...) for positive lookbehind. Hence:

(?<=@)[a-zA-Z0-9-_]+

Play with it on Regex101 if you'd like.

Upvotes: 5

Related Questions