Reputation: 193
I'm trying to make a regex that removes me in my text email: [email protected].
example: I request information on your project email: [email protected]
So I did this that captures me "email: [email protected]"
message ="I request information on your project email. [email protected]"
message.gsub!("/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i")
it returns me nothing, and I wish there was just in the message text.
thanks
Upvotes: 0
Views: 101
Reputation: 37409
Your code has several problems:
"email: ..."
, but you message has "email. ..."
.You use gsub!
, with one parameter, which is not the classic use case, and returns an Enumerator
. The classic use case expects a second parameter, which indicates to what you want to substitute the found matches:
Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. If no block and no replacement is given, an enumerator is returned instead.
You pass a string to the gsub!
- "/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i"
, which is different than sending a regex. To pass a regex, you need to drop the quotes around it: /(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i
So a fix to your code would look like this:
message ="I request information on your project email: [email protected]"
message.gsub!(/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i, '')
# => "I request information on your project "
Also note I changed your code to use gsub
instead of gsub!
, since gsub!
changes the underlying string, instead of creating a new one, and unless you have a good reason to do that, it is not encouraged to mutate the input arguments...
Upvotes: 0
Reputation: 611
If you want to remove the email from the text use String#sub
message = "I request information on your project email. [email protected]"
message.sub!(/[A-Za-z]{5}:\s[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/, '')
# => "I request information on your project "
Upvotes: 0
Reputation: 11244
Try this. This should work for both uppercase, lowercase and emails appear in the middle of the string.
email = /[A-Za-z]{5}:\s[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/
s = "I request information on your project email: [email protected]"
s.match(email).pre_match #=> "I request information on your project "
s2 = "This email: [email protected] is in the middle"
s2.match(email).pre_match #=> "This "
s2.match(email).post_match #=> " is in the middle"
But there are more cases not covered e.g. email:
followed by many spaces
Upvotes: 1