Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5aab1e6

Browse files
authored
Merge pull request #173 from nobu/email_regexp-refine
Improve performance of `URI::MailTo::EMAIL_REGEXP`
2 parents c5974f0 + 7363a13 commit 5aab1e6

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/uri/mailto.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ class MailTo < Generic
5252
HEADER_REGEXP = /\A(?<hfield>(?:%\h\h|[!$'-.0-;@-Z_a-z~])*=(?:%\h\h|[!$'-.0-;@-Z_a-z~])*)(?:&\g<hfield>)*\z/
5353
# practical regexp for email address
5454
# https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
55-
EMAIL_REGEXP = /\A(?!\.)(?!.*\.{2})[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+(?<!\.)@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/
55+
EMAIL_REGEXP = %r[\A#{
56+
atext = %q[(?:[a-zA-Z0-9!\#$%&'*+\/=?^_`{|}~-]+)]
57+
}(?:\.#{atext})*@#{
58+
label = %q[(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)]
59+
}(?:\.#{label})*\z]
5660
# :startdoc:
5761

5862
#

test/uri/test_mailto.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,22 @@ def test_check_to
210210
end
211211
end
212212

213+
def test_email_regexp
214+
re = URI::MailTo::EMAIL_REGEXP
215+
216+
rate = 1000
217+
longlabel = '.' + 'invalid'.ljust(63, 'd')
218+
endlabel = ''
219+
pre = ->(n) {'a@invalid' + longlabel*(n*rate) + endlabel}
220+
assert_linear_performance(1..10, pre: pre) do |to|
221+
re =~ to or flunk
222+
end
223+
endlabel = '.' + 'email'.rjust(64, 'd')
224+
assert_linear_performance(1..10, pre: pre) do |to|
225+
re =~ to and flunk
226+
end
227+
end
228+
213229
def test_to_s
214230
u = URI::MailTo.build([nil, 'subject=Ruby'])
215231

0 commit comments

Comments
 (0)