Regular expression to detect mentions but not detect email messages

I have the following code:

preg_match('/@([^@ ]+)/', $image->caption->text, $matches)

and I wanted to basically find mentions in the line. However, the problem now is that it gets confused with the email address, so that it detects the email as a mention, so for example, if I have aksdjasd@yahoo.com, then this is considered a coincidence. I assume that I want to say here that there must be space in front of the @ sign. But how do I put this into this regular expression?

EDIT: I also wanted to detect @mentions at the beginning of the line as well

+4
source share
3 answers

there must be a space before the @ sign

lookbehind ( OP ):

preg_match('/(?<= |^)@[^@ ]+/', $image->caption->text, $matches);

+4

:

preg_match('/(?<=\W|^)@(\w+)/', "@Easy? No.@anubhava try harder! @\t", $matches);
preg_match('/(?<=\W|^)@(\w+)/', "Easy? No.@anubhava try harder! @\t", $matches);
preg_match('/(?<=\W|^)@(\w+)/', "Easy? No.anubhava try harder! e@m @\t", $match);

@Easy, @anubhava, .

+1

look behinds .

: preg_match('/(?<![^\s])@([^@\s]+)/', $image->caption->text, $matches);

, \s , @. , @stuff<NEWLINE><nonmatch>. , . .

, , , . .

I think that just checking the space can have risks. I think you can check any whitespace just in case the mention is at the very beginning of the line.

0
source

Source: https://habr.com/ru/post/1537518/


All Articles