Mark
Mark

Reputation: 3859

Regex to include strings that start with @ but not in the middle of string?

I'm trying to match @username similar to twitter. The regex I'm using right now: "([@])(\S+)" works decently well for this.

However limitations are as follows [email protected] matches test.com

Now I want to completly exclude [email protected]

However, some of my users have usernames [email protected] and want to include them if they actually have an @ in front of that email username.

So @[email protected] should match

Summary: Needs to match:

@username

@test

@[email protected]

Do not want to match:

[email protected]

Upvotes: 1

Views: 840

Answers (4)

Qtax
Qtax

Reputation: 33928

I'd recommend using a negative lookbehind, eg:

(?<!\S)@(\S+)

This will not include any possible space before the @foo, so you can replace it without issue.

Upvotes: 2

Jon
Jon

Reputation: 4736

Making as an answer, you don't want to check for @ in middle of the text, but it needs a space in front, so use (\s|^)+([@])(\S+)

Upvotes: 1

sasi_personal
sasi_personal

Reputation: 249

^@.* The above regular expression matches what you are looking for

Upvotes: 0

Pete Garafano
Pete Garafano

Reputation: 4923

The regex would look something like this: ^@.* The ^ will anchor you to the start of the line or the string. Be sure to check out OverAPI Regex, their cheat sheets are very nice.

Upvotes: 0

Related Questions