[英]Ruby Regular Expression Excluding
@message_to = 'bob@google.com'
@cleaned = @message_to.match(/^(.*)+@/)
@cleaned is returning bob@, where I want it to return just bob. @cleaned返回bob @,我希望它只返回bob。 Am I doing the regex right with ruby? 我在用红宝石做正则表达式吗?
Thanks 谢谢
No need much regular expression 无需太多正则表达式
>> @message_to = "bob@google.com"
=> "bob@google.com"
>> @message_to.split("@",2)
=> ["bob", "google.com"]
>> @message_to.split("@",2)[0] if @message_to["@"]
=> "bob"
>>
You want this: 你要这个:
@cleaned = @message_to.match(/^(.*)+@/)[1]
match
returns a MatchData
object and the string version of that is the entire match, the captured groups are available starting at index 1 when you treat the MatchData
as an array . match
返回一个MatchData
对象,并且该字符串的版本是整个match,将MatchData
视为数组时,捕获的组从索引1开始可用。
I'd probably go with something more like this though: 我可能会选择类似这样的东西:
@cleaned = @message_to.match(/^([^@]+)@/)[1]
有一个较短的解决方案:
@cleaned = @message_to[/[^@]+/]
The most obvious way to adjust your code is by using a forward positive assertion. 调整代码的最明显方法是使用正向肯定断言。 Instead of saying "match bob@
" you're now saying "match bob
, when followed by a @
" 现在,您不是说“ match bob@
”,而是说“ match bob
,后跟一个@
”
@message_to = 'bob@google.com'
@cleaned = @message_to.match(/^(.*)+(?=@)/)
A further point about when to use and not to use regexes: yes, using a regex is a bit pointless in this case. 关于何时使用和不使用正则表达式的另一点:是的,在这种情况下,使用正则表达式毫无意义。 But when you do use a regex, it's easier to add validation as well: 但是,当您确实使用正则表达式时,也更容易添加验证:
@cleaned = @message_to.match(/^(([-a-zA-Z0-9!#$%&'*+\/=?^_`{|}~]+.)*[-a-zA-Z0-9!#$%&'*+\/=?^_`{|}~]+(?=@)/)
(and yes, all those are valid in email-adresses) (是的,所有这些均在电子邮件地址中有效)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.