tags:

views:

227

answers:

4

I want to match either @ or 'at' in a regex. Can someone help? I tried using the ? operator, giving me /@?(at)?/ but that didn't work

+12  A: 

Try:

/(@|at)/

This means either @ or at but not both. It's also captured in a group, so you can later access the exact match through a backreference if you want to.

Michael Myers
would this handle cases where the email address is something like [email protected], or latitudeataddress.com?
Josh E
Why wouldn't it? What do you mean by "handle"?
Michael Myers
would it produce false positive matches is what I'm asking I guess.
Josh E
Of course it would produce false positives! Regular expressions can't read your mind.
innaM
right... so then would the OP be better served with a regex that attempts to reduce that possiblity in your opinion? I think that you could improve upon it, but at the cost of increased complexity. Would that be worth it though?
Josh E
+8  A: 
/(?:@|at)/

mmyers' answer will perform a paren capture; mine won't. Which you should use depends on whether you want the paren capture.

chaos
+1 for an alternative and for spelling my name right.
Michael Myers
Aw, thanks. Have a +1 toward the Enlightened badge you'll be getting for this one. :)
chaos
A: 

have you tried

@|at

that works for (in the .NET regex flavor) the following text

[email protected] johnsmithatgmail.com

Josh E
why the plus after the "@"? that will match multiple @'s in a row too...
Kip
sorry - removed the + in there after editing
Josh E
+3  A: 

if that's only 2 things you want to capture, no need regex

if ( strpos($string,"@")!==FALSE || strpos($string,"at") !==FALSE ) {
  # do your thing
}
ghostdog74
True. I was assuming this was part of something bigger, but if not, this is probably better.
Michael Myers