How do you match one of two words in a regular expression?

Viewed 66671

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

5 Answers

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.

/(?:@|at)/

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

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

if ( strpos($string,"@")!==FALSE || strpos($string,"at") !==FALSE ) {
  # do your thing
}

have you tried

@|at

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

johnsmith@gmail.com johnsmithatgmail.com

What about:

^(\w*(@|at))

For:

  • johnsmith@ gmail.com
  • johnsmithatgmail.com
  • jonsmith@ atgmail.com
Related