Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclusive Or in Regular Expression

Tags:

regex

xor

Looking for a bit of regex help. I'd like to design an expression that matches a string with "foo" OR "bar", but not both "foo" AND "bar"

If I do something like...

/((foo)|(bar))/ 

It'll match "foobar". Not what I'm looking for. So, how can I make regex match only when one term or the other is present?

Thanks!

like image 937
SocialCensus Avatar asked Oct 29 '08 15:10

SocialCensus


People also ask

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Can we use or in regex?

Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.


1 Answers

This is what I use:

/^(foo|bar){1}$/ 

See: http://www.regular-expressions.info/quickstart.html under repetition

like image 56
Tristan Avatar answered Oct 02 '22 02:10

Tristan