开发者

Ruby Regular Expression Excluding

开发者 https://www.devze.com 2023-02-14 06:52 出处:网络
@开发者_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?
@开发者_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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号