Alternation Matches



The literal | is used to find one or the other match. Example cat|mat matches category and mathew but not tamtac As a practical example consider the case when we want to see if a given pattern matches a valid website name.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 9
Alternation match
********************************************************
*/
var pattern1=new RegExp("com|org|net");
var string1 = new Array(4);
string1[0] = "http://google.com";
string1[1] = "http://google.net";
string1[2] = "http://google.org";
string1[3] = "http://google.cox";
var i;
for(i=0; i<=3; i++)
{

if (pattern1.test(string1[i]))
{
document.write(string1[i], " -> match found with com|org |net","<br\>");
}
else
{
document.write(string1[i], " -> match not found with com|org|net","<br\>");
}
}
//-->
</script>
</body>
</html>


Try this Example online


You can try this example online at - here .

The regular expression RegExp("com|org|net") will find a match if the given string contains com , org or net.

The script gives the following output.

http://google.com -> match found with com|org |net
http://google.net -> match found with com|org |net
http://google.org -> match found with com|org |net
http://google.cox -> match not found with com|org|net
A real world example of a valid website match is more complex than this and this example helps you understand the concept of alternation

A note on Eager Match



The regular expression starts matching from the left to right. Consider for example the regular expression RegExp("John|Johnson") trying to match the string "My big brother is Johnson". When trying to match the string the regular expression engine stops as soon as it finds the match for John. It then does not attempt to match the second alternative Johnson. We term it as the fact that regular expression engine is an eager engine. If we want to give prefernce to Johnson, we could have written the regular expression as RegExp("Johnson|John").