@message_to = 'bob@google.com'
@cleaned = @message_to.match(/^(.*)+@/)
@cleaned is returning bob@, where I want it to return just bob. Am I doing the regex right with ruby?
Thanks
@message_to = 'bob@google.com'
@cleaned = @message_to.match(/^(.*)+@/)
@cleaned is returning bob@, where I want it to return just 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.
I'd probably go with something more like this though:
@cleaned = @message_to.match(/^([^@]+)@/)[1]
An even shorter code than mu_is_too_short would be:
@cleaned = @message_to[/^([^@]+)@/, 1]
The String#[] method can take a regular expression.
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 @
"
@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)