Given inputs like the following
bob - invalid
bob. - invalid
bob.edu - valid
bob.com - valid
bob.newco.com - valid
In Ruby, I'd like a way to first determine if there is a period, if there is I want everything after the last period?
I tried doing
domain_ext = search_input.split('.').last
Problem is, if the input is roger开发者_开发知识库.
that is returning 5, thinking roger
is the ext. I don't know how to tell Ruby only after the last period?
The same regex can be used to filter out domains with a TLD, and return the TLD:
/\.(.+?)$/
Here are some use examples:
domains = %w[ foo foo. foo.com ].select{ |d| d[/\.(.+?)$/, 1] }
=> ["foo.com"]
domains = %w[ foo foo. foo.com ].map{ |d| d[/\.(.+?)$/, 1] }
=> [nil, nil, "com"]
Based on Sawa's comment:
%w[ foo foo. foo.com foo.bar.com ].select{ |d| d[/(?<=\.)([a-z0-9-]+?)$/i, 1] }
=> ["foo.com", "foo.bar.com"]
%w[ foo foo. foo.com foo.bar.com ].map{ |d| d[/(?<=\.)([a-z0-9-]+?)$/i, 1] }
=> [nil, nil, "com", "com"]
a = %w[
bob
bob.
bob.edu
bob.com
bob.newco.com
]
a.each{|str| p str[/\.([^.]+)\z/, 1]}
will give you
nil
nil
"edu"
"com"
"com"
You can just do a substring based on the last index of "."
domain_ext = search_index[search_index.rindex('.')+1..-1]
The above means:
search_index.rindex('.')+1 #Reverse index of "." + 1
search_index.rindex('.')+1..-1 # From that point to the end of the string
search_index[] #Simply takes a substring
How about this:
domain_ext = search.split('.').drop(1).last
Which yields, on your examples:
> 'bob'.split('.').drop(1).last
=> nil
> 'bob.'.split('.').drop(1).last
=> nil
> 'bob.edu'.split('.').drop(1).last
=> "edu"
> 'bob.com'.split('.').drop(1).last
=> "com"
> 'bob.newco.com'.split('.').drop(1).last
=> "com"
> '@gmail.'.split('.').drop(1).last
=> nil
if a trailing period is ok, /(.*)\.(.+)/
will match on the second group, if no trailing is allowed, try /(.*)\.(.*)/
精彩评论