Logue1021
Logue1021

Reputation: 54

Regex remove a first period

I'm trying to remove a period prior to the "@" symbol from an email. I got:

array[0][2].gsub(/\./, '').strip

which removes both periods; "[email protected]" becomes "anemail@testcom", while I'm looking for it to become "[email protected]". I can't remove just the single period by itself. What am I doing wrong?

Upvotes: 0

Views: 869

Answers (3)

glenn mcdonald
glenn mcdonald

Reputation: 15488

Don't make this more complicated by trying to make it short. Just write it the way you mean it:

a, b = address.split('@')
cleaned = [a.delete('.'), b].join('@')

Upvotes: 0

zx81
zx81

Reputation: 41838

result = subject.gsub(/\.(?=\S+@)/, '')

Explanation

  • \. matches a period
  • the (?=\S+@) lookahead asserts that what follows is any non-whitespace chars followed by an arrobas
  • we replace with the empty string

Reference

Upvotes: 0

Santhosh
Santhosh

Reputation: 29124

If there are no periods before @ or if there are more than one period, you can use this regex

email = "[email protected]"
email.gsub(/\.(?=[^@]*\@)/, '')
# => "[email protected]"

Regex explanation: period followed by zero or more occurrence of any character other than @, followed by an @

If only the first occurrence of a period before @ has to be removed, you can use the same regex with sub instead of gsub

Upvotes: 1

Related Questions