Regex.Matches Idn

StewartBW 1,145 Reputation points
2024-08-01T12:02:02.1266667+00:00

Hello

I'm using this to collect emails from string:

Dim mc As MatchCollection = Regex.Matches(src, "([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,9})", RegexOptions.CultureInvariant Or RegexOptions.IgnoreCase Or RegexOptions.Multiline)

This will not work on Idn domains, however, there's a validator sample here:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

How can I get regex matches and assign to MatchCollection for Idm domains using the above mentioned regex which is:

"^[^@\s]+@[^@\s]+\.[^@\s]+$"

Thanks :)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,899 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,722 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 117K Reputation points
    2024-08-01T13:04:11.44+00:00

    To support more forms of e-mails, try this pattern (in VB):

    "([\p{L}\p{N}_\-\.]+)@([\p{L}\p{N}_\-]+[\.\u3002\uFF0E\uFF61])+([\p{L}\p{N}_\-]+)"

    If it does not always work, show examples.

    0 comments No comments

  2. Jiachen Li-MSFT 31,166 Reputation points Microsoft Vendor
    2024-09-20T06:51:10.74+00:00

    To match email addresses that include Internationalized Domain Names (IDNs), you can use a more comprehensive regular expression. The regex you mentioned (^[^@\s]+@[^@\s]+\.[^@\s]+$) is a good start, but it doesn’t cover all the nuances of IDNs.

    Here’s an updated version of your code to handle IDNs:

    Dim mc As MatchCollection = Regex.Matches(src, "^[^\s@]+@[^\s@]+\.[^\s@]+$", RegexOptions.CultureInvariant Or RegexOptions.IgnoreCase Or RegexOptions.Multiline)
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  3. Bruce (SqlWork.com) 64,826 Reputation points
    2024-09-20T17:50:42.9366667+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.