简体   繁体   English

红宝石正则表达式,以确保电子邮件输入格式

[英]ruby regex to ensure email entering format

Are we suppose to use regex with for loop? 我们是否应该将正则表达式与for循环一起使用? For example If I want to ensure the user entering bunch of email in a text-box in the format like below, What is the best way to do it ? 例如,如果我要确保用户在文本框中以如下格式输入一堆电子邮件,什么是最好的方法?

Zoo bbb <zoo@email.com>, Alan T <at@gmail.xxx>, ........

How do we extract the information and put in names[], emails[].? 我们如何提取信息并放入名称[],电子邮件[]。

If you wanted to use regex the following pattern would match: 如果要使用正则表达式,则以下模式将匹配:

<([\w+\.\@]+)>+


Match 1
1.  zoo@email.com
Match 2
1.  at@gmail.xxx

You can test it out on: http://rubular.com 您可以在以下网址进行测试: http//rubular.com

What you would do is count the matches found by using scan 您要做的是使用scan计数找到的匹配项

here is the example code i put together 这是我放在一起的示例代码

s = "Zoo bbb <zoo@email.com>, Alan T <at@gmail.xxx>"

names = []
emails = []

s.scan(/[\s]?([\w\s]+)<([\w+\.\@]+)>+/).each do | m |
  names << m[0]
  emails << m[1]
end

puts "names = #{names}"
puts "emails = #{emails}"

output: 输出:

names = ["Zoo bbb ", "Alan T "]
emails = ["zoo@email.com", "at@gmail.xxx"]

Try this: 尝试这个:

test_string = "Zoo bbb <zoo@email.com>, Alan T <at@gmail.xxx>, James B <james.bond@m5.gov.co.uk>"

# Create regexp to match emails given this format "Alan T <at@gmail.xxx>, ..."
regexp = /\s*,?\s*(.*?)<(.*?)>/

# Scan string for regexp matches
matches = test_string.scan(regexp)

# Let's see what the matches are...
p matches # [["Zoo bbb ", "zoo@email.com"], ["Alan T ", "at@gmail.xxx"], ["James B ", "james.bond@m5.gov.co.uk"]] 

# Iterating over matches is easy
matches.each do |match_array|
    puts "Name:\t #{match_array[0]}"
    puts "Email:\t #{match_array[1]}"
end

# To extract all names and emails into individual arrays:
names = []
emails = []
matches.each do |match_array|
    names << match_array[0]
    emails << match_array[1]
end

p names # ["Zoo bbb ", "Alan T ", "James B "] 
p emails # ["zoo@email.com", "at@gmail.xxx", "james.bond@m5.gov.co.uk"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM