punjabi revolution tutorial Javascript regular expression part 3

Here we understand the usage of () brackets in regular expression pattern. the () brackets are used to group the letters as single entity. for instance, take the previous example of vehicle number plate

Here in pattern /^[A-Z]{3}-[0-9]{5}$/, if we make modification as /^[A-Z]{3}-9191{2}$/ then what does it mean?. it means any format with three upper case letter followed by digit 91911 is allowed. the curly brackets {} for frequency would be applied only on the last digit 1. so if we want to apply it on the whole set of digits, we would have to use () brackets. so the pattern /^[A-Z]{3}-(9191){2}$/ means, three uppper case letters followed by 91919191. i.e. 9191 was repeated two times. similarly we can make it more expressive like /^[A-Z]{3}-[9191{1-3}$/. It means, three upper case letters followed 1,2 or three repetitions of 9191.  for instance, following are all allowed

EEE-919191919191

EEE-91919191

EEE-9191

Here is table showing how to specify the repetition of previous letter or group of letters indicated by () by using curly braces {}.

{x} Match exactly x occurrences of a regular expression. /\d{5}/ matches 5 digits.
{x,} Match x or more occurrences of a regular expression. /\s{2,}/ matches at least 2 whitespace characters.
{x,y} Matches x to y number of occurrences of a regular expression. /\d{2,4}/ matches at least 2 but no more than 4 digits.
? Match zero or one occurrences. Equivalent to {0,1}. /a\s?b/ matches “ab” or “a b”.
* Match zero or more occurrences. Equivalent to {0,}. /we*/ matches “w” in “why” and “wee” in “between”, but nothing in “bad”
+ Match one or more occurrences. Equivalent to {1,}. /fe+d/ matches both “fed” and “feed”

Here is a sample code .

Another symbol is the or | symbol. it gives options between two patterns. A simple example is

 

 

/^[A-Z]{3}-(9191)|(1010)$/ will accepts either three upper case letter followed by 9191 or followed by 1010. so in a scenario, where we have to select an option out of multiple given options, we can use | symbol.

Try out the given codes and should you have any issue, please write in below comments area.

 

Leave a Reply

Your email address will not be published. Required fields are marked *