开发者

How to detect that a certain string is not an email address but a twitter id?

开发者 https://www.devze.com 2023-03-08 01:53 出处:网络
Is there a way to differentiate between an email address and a twitter id? Both use the \'@\' character and the email regex will be contained by the twitter id regex.

Is there a way to differentiate between an email address and a twitter id?

Both use the '@' character and the email regex will be contained by the twitter id regex.

What's the best way to approach thi开发者_StackOverflow社区s?

Should I require a whitespace before the '@' character in order to identify that it's a twitter id?


Not entirely sure which characters are allowed in twitter usernames, but basically like so:

/(?:^|\s)@[a-zA-Z0-9_.-]+\b/


You can test that it's preceded by whitespace using (?<=\s) and then check for the valid characters of twitter IDs which are only [A-Za-z0-9_].

That gives you a resulting regex of: (?<=\s|^)@[A-Za-z0-9_]+

You could eventually add a check for a dot, comma or whitespace after it to check that it's properly formatted within a sentence and not some weird artifact:

(?<=\s|^)@[A-Za-z0-9_]+(?=[\s.,])

Note that the lookbehind and lookahead (?<= and ?=) might not work in your language of choice, but I'll assume it does since you didn't specify.


Email addresses never start with an @, while twitter ids always do.

isTwitter = address[0] == '@'


A twitter id wouldn't pass an email regex check.

Regular email:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

twitter won't have the last characters:

^@[A-Za-z0-9_]+$

So check if it's a valid email, if not, check if it's a valid twitter ID

Farther reading:

How to Find or Validate an Email Address

0

精彩评论

暂无评论...
验证码 换一张
取 消