Alternate Patterns in Regular Expressions

A frequent requirement when validating user input is to allow for one of several substrings in the target text. To accomplish this in regex we define alternate patterns in the expression. Alternate patterns are defined by separating alternate pieces of acceptable text with a solid pipe, | character.

For instance the pattern (Spider|Super)man matches "Spiderman" and "Superman" but not "Miracleman". Great caution is required when specifying alternation patterns. The pattern above would quite happily treat "SpiderSuperman" as being valid. Similarly the pattern Windows 95|NT|2000|XP\b will validate the string "Windows 2000XP". The patterns \b(Spider|Super)man and Windows (95|NT|2000|XP)\b on the other hand will correctly report "SpiderSuperman" and "Windows 2000XP" as being invalid. Why? Because the subexpression grouping preceded/followed by the \b specifier instructs the regex engine to only accept alternatives that occur at a word boundary.

Regular Expression Sandbox
Model
Data

Do not wrap the model expression in a /.../ pair. The characters ^$.?*!+:=()[]{}|\\ must be escaped - except when then occur inside a character class. Invalid characters will be grayed out.
Result Left Text Match Right Text
       

Download
Jump To...

Colophon