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


Question

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

1
34
7/27/2009 9:16:52 PM

Accepted Answer

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.

58
7/27/2009 2:34:52 PM

/(?:@|at)/

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon