@开发者_JAVA技巧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]
There is a shorter solution:
@cleaned = @message_to[/[^@]+/]
An even shorter code than mu_is_too_short would be:
@cleaned = @message_to[/^([^@]+)@/, 1]
The String#[] method can take a regular expression.
The simplest RegEx I got to work in the IRB console is:
@message_to = 'bob@google.com'
@cleaned = @message_to.match(/(.+)@/)[1]
Also from this link you could try:
@cleaned = @message_to.match(/^(?<local_part>[\w\W]*?)@/)[:local_part]
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)
精彩评论