Regex @mention including .com without final

Viewed 24

How to match a @mention with and without suffix domain name ('@leïa' and '@Leïa@starwars.com' are valid) but without to get the last '.'?

Regex: /@([A-Za-z0-9_çéàèùâêîôûëïüÇÉÀÈÙÂÊÎÔÛËÏÜ@.]+)/ig

Sample:

@Luke is the brother of @Leïa@starwars.com, and they are the both children of @DarthVather.

Expected:

@Luke, @Leïa@starwars.com and @DarthVather (without the final '.')

1 Answers

You can use

@[A-Za-z0-9_çéàèùâêîôûëïüÇÉÀÈÙÂÊÎÔÛËÏÜ]+(?:[.@][A-Za-z0-9_çéàèùâêîôûëïüÇÉÀÈÙÂÊÎÔÛËÏÜ]+)*

See the regex demo.

Details:

  • @ - a @ char
  • [A-Za-z0-9_çéàèùâêîôûëïüÇÉÀÈÙÂÊÎÔÛËÏÜ]+ - one of the selected letters, digits, underscores
  • (?:[.@][A-Za-z0-9_çéàèùâêîôûëïüÇÉÀÈÙÂÊÎÔÛËÏÜ]+)* - zero or more occurrences of a . or @ followed with one of the selected letters, digits, underscores.

In Python 3, you can simplify this to

results = re.findall(r'@\w+(?:[.@]\w+)*', text)

You do not need re.U / re.UNICODE since it is on by default.

Related