50

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

Adrian Sarli
  • 2,286
  • 3
  • 20
  • 31
  • [Regular expression containing one word or another](http://stackoverflow.com/q/17166618/995714) – phuclv Mar 11 '16 at 09:29

5 Answers5

80

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
  • 188,989
  • 46
  • 291
  • 292
  • would this handle cases where the email address is something like atproperties@something.com, or latitudeataddress.com? – Josh E Jul 27 '09 at 14:50
  • Why wouldn't it? What do you mean by "handle"? – Michael Myers Jul 27 '09 at 14:56
  • would it produce false positive matches is what I'm asking I guess. – Josh E Jul 27 '09 at 15:17
  • 1
    Of course it would produce false positives! Regular expressions can't read your mind. – innaM Jul 27 '09 at 15:18
  • 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 Jul 27 '09 at 15:21
43
/(?:@|at)/

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

chaos
  • 122,029
  • 33
  • 303
  • 309
4

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
  • 327,991
  • 56
  • 259
  • 343
3

have you tried

@|at

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

johnsmith@gmail.com johnsmithatgmail.com

Josh E
  • 7,390
  • 2
  • 32
  • 44
  • This will also match `jonsmith@atgmail.com` Is there a way to match either one but not both in a row? My use case is routing for someone with a nickname. I need to match `www.domain.com/name` and `www.domain.com/nickname` but not `www.domain.com/namenickname`. – Costa Michailidis May 14 '15 at 23:30
1

What about:

^(\w*(@|at))

For:

  • johnsmith@ gmail.com
  • johnsmithatgmail.com
  • jonsmith@ atgmail.com
Erick Asto Oblitas
  • 1,399
  • 3
  • 21
  • 47