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
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

[email protected] johnsmithatgmail.com

Josh E
  • 7,390
  • 2
  • 32
  • 44
  • This will also match `[email protected]` 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