简体   繁体   English

如何从ruby中的字符串中提取子字符串?

[英]How can I extract the substring from a string in ruby?

I have a repeated string="I will email you at xxx@gmail.com" and I want to pull out just the actual email address. 我有一个重复的string="I will email you at xxx@gmail.com" ,我只想提取实际的电子邮件地址。

How can I pull just the email out? 我怎样才能只提取电子邮件?

Note: Ideally, I'd also like to deal with user-error where the format may be "I will email you at my email xxx@gmail.com" . 注意:理想情况下,我还想处理用户错误,其格式可能是"I will email you at my email xxx@gmail.com" In this case, the user input "my email xxx@gmail.com" and I just want the email address. 在这种情况下,用户输入“我的电子邮件xxx@gmail.com”,而我只需要该电子邮件地址。

Relatively permissive regex that will work with your example: 相对宽松的正则表达式适用于您的示例:

"I will email you at xxx@gmail.com".match(/\b\S+@\S+\b/).to_s
#=> "xxx@gmail.com"

See also this RFC-compliant regex . 另请参阅此符合RFC的正则表达式

You can do this: 你可以这样做:

[6] pry(main)> string="I will email you at xxx@gmail.com"
=> "I will email you at xxx@gmail.com"
[7] pry(main)> string.scan(/[A-Za-z\d_\-\.+]+@[A-Za-z\d_\-\.]+\.[A-Za-z\d_\-]+/)
=> ["xxx@gmail.com"]
[8] pry(main)> str2 = "I will email you at my email xxx@gmail.com"
=> "I will email you at my email xxx@gmail.com"
[9] pry(main)> string.scan(/[A-Za-z\d_\-\.+]+@[A-Za-z\d_\-\.]+\.[A-Za-z\d_\-]+/)
=> ["xxx@gmail.com"]

There's some good reading on this subject at " How to Find or Validate an Email Address " 在“ 如何查找或验证电子邮件地址 ”中对此主题有一些不错的阅读

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

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