Reputation: 26212
I'm trying to avoid emails in my input field boxes, so I'm using multiple regex for this, I got one that is matching more than I want, this is the regex :
(at( )*\w+(\b\.ie\b|\b\ .ie\b))
And its supposed to match attempts like email at domain.ie but I got also this part matching :
also what a tie
they are
How can I modify this regex not to match this case?
I tried this :
(at( )[a-z^\s]\w+(\b\.ie\b|\b\ .ie\b))
and couple of more things, still I get the same match, how can I still keep the matching that I want but to avoid this case
Upvotes: 0
Views: 87
Reputation: 121
To match something like "at foo.ie" or "at foo .ie", something as simple as this will work: /\bat +\w+ ?\.ie\b/
Upvotes: 1
Reputation: 27548
To avoid the unexpected match, try using a literal period \.
in your regular expression. Testing that against a few inputs looks like it gets what you want:
tests = [
{:text => 'at domain.ie', :expected => true},
{:text => 'at something.ie', :expected => true},
{:text => 'at foo.ie', :expected => true},
{:text => 'also what a tie they are', :expected => false}
]
regex = /\bat\s+\w+\s?\.ie\b/
tests.each do |test|
text = test[:text]
expect_match = test[:expected]
matched = false
if text =~ regex
matched = true
end
if expect_match == matched
puts "OK: expected=#{expect_match} == #{matched} for regex=#{regex} vs text=#{text}"
else
puts "NOT OK: expected=#{expect_match} != #{matched} for regex=#{regex} vs text=#{text}"
end
end
If you have more test cases, it should be easy to add them to the above code - though you may wish to make a more formal test using something like rspec.
Upvotes: 0