我们是否应该将正则表达式与 for 循环一起使用?例如,如果我想确保用户以如下格式在文本框中输入一堆电子邮件,那么最好的方法是什么?
Zoo bbb <zoo@email.com>, Alan T <at@gmail.xxx>, ........
我们如何提取信息并输入名称[]、电子邮件[]。?
我们是否应该将正则表达式与 for 循环一起使用?例如,如果我想确保用户以如下格式在文本框中输入一堆电子邮件,那么最好的方法是什么?
Zoo bbb <zoo@email.com>, Alan T <at@gmail.xxx>, ........
我们如何提取信息并输入名称[]、电子邮件[]。?
如果您想使用正则表达式,则以下模式将匹配:
<([\w+\.\@]+)>+
Match 1
1. zoo@email.com
Match 2
1. at@gmail.xxx
您可以在以下位置进行测试:http ://rubular.com
您要做的是计算使用找到的匹配项scan
这是我放在一起的示例代码
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}"
输出:
names = ["Zoo bbb ", "Alan T "]
emails = ["zoo@email.com", "at@gmail.xxx"]
尝试这个:
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"]