Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve the regex used for NameEmail validation #6125

Merged
merged 1 commit into from Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions pydantic/networks.py
Expand Up @@ -376,7 +376,15 @@ def _validate(cls, __input_value: NetworkType, _: core_schema.ValidationInfo) ->
return cls(__input_value) # type: ignore[return-value]


pretty_email_regex = re.compile(r' *([\w ]*?) *<(.+?)> *')
def _build_pretty_email_regex() -> re.Pattern:
name_chars = r'[\w!#$%&\'*+\-/=?^_`{|}~]'
unquoted_name_group = fr'((?:{name_chars}+\s+)*{name_chars}+)'
quoted_name_group = r'"((?:[^"]|\")+)"'
email_group = r'<\s*(.+)\s*>'
return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*')


pretty_email_regex = _build_pretty_email_regex()


def validate_email(value: str) -> tuple[str, str]:
Expand All @@ -395,7 +403,8 @@ def validate_email(value: str) -> tuple[str, str]:
m = pretty_email_regex.fullmatch(value)
name: str | None = None
if m:
name, value = m.groups()
unquoted_name, quoted_name, value = m.groups()
name = unquoted_name or quoted_name

email = value.strip()

Expand Down
3 changes: 3 additions & 0 deletions tests/test_networks.py
Expand Up @@ -751,6 +751,8 @@ class Model(BaseModel):
('аррӏе@example.com', 'аррӏе', 'аррӏе@example.com'),
('xn--80ak6aa92e@example.com', 'xn--80ak6aa92e', 'xn--80ak6aa92e@example.com'),
('葉士豪@臺網中心.tw', '葉士豪', '葉士豪@臺網中心.tw'),
('"first.last" <first.last@example.com>', 'first.last', 'first.last@example.com'),
("Shaquille O'Neal <shaq@example.com>", "Shaquille O'Neal", 'shaq@example.com'),
],
)
def test_address_valid(value, name, email):
Expand Down Expand Up @@ -785,6 +787,7 @@ def test_address_valid(value, name, email):
('foobar <foobar@example.com>>', None),
('foobar <<foobar<@example.com>', None),
('foobar <>', None),
('first.last <first.last@example.com>', None),
],
)
def test_address_invalid(value, reason):
Expand Down