Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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

like image 345
Adrian Sarli Avatar asked Jul 27 '09 14:07

Adrian Sarli


People also ask

How do you match a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do you combine two regular expressions?

to combine two expressions or more, put every expression in brackets, and use: *? This are the signs to combine, in order of relevance: ?

What regular expression would you use to match a single character?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is the regular expression for keywords?

A regular expression is a template or pattern used to find multiple different strings. Regular expressions can be used to identify groups of related URLs in access limiting filters and exceptions from these and as a more flexible form of a keyword to assign URLs to categories for blocking.


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

like image 165
Michael Myers Avatar answered Oct 07 '22 18:10

Michael Myers


/(?:@|at)/ 

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

like image 37
chaos Avatar answered Oct 07 '22 18:10

chaos