Quantifiers (Repetition)

To match 3 digit patterns, we can use [0-9][0-9][0-9]. What if we have n digit patterns? We have to write [0-9] n times, but that is a waste of time. Here is when quantifiers come for help.

  1. Limiting repetitions({min, max}): To match n digit patterns, we can simply write [0-9]{n}. Instead of n, by providing minimum and maximum values as-[0-9]{min, max}, we can match a pattern repeating min to max times.

    Let's see an example to match all numbers between 1 to 999.

    Note: If you don't write the upper bound({min,}), then it basically means, there is no limit for maximum repetitions.

  2. + quantifier: It is equivalent to {1,}-at least one occurrence.

  3. *quantifier: It is equivalent to {0,}-zero or more occurrences.

  4. ? quantifier: It is equivalent to {0,1}, either zero or one occurrence. ? is very useful for optional occurrences in patterns.
  5. Let's see an example to match negative and positive numbers.

Now, you may be thinking, what if we want to match characters like *, ?, +, {, } in the text, they are special characters. Check it out in the appendix.

Problems

  1. Find out a regex to match positive integers or floating point numbers with exactly two characters after the decimal point.

    Answer: \d+(\.\d\d)?

  2. Predict the output of the following regex:
    RegEx: [abc]{2,}
    Text: aaa abc abbccc avbcc

    Answer:

Nature of Quantifiers

HTML tag is represented as <tag_name>some text</tag_name>. For example, <title>Regular expression</title>

So, can you figure out an expression that will match both <tag_name> & </tag_name>?

Most of the people will say, it is <.*>. But it gives different result.

So, rather than matching up till first >, it matches the whole tag. So, quantifiers are greedy by default. It is called Greediness!.

To solve this issue, we use ? quantifier and it is called lazy matching. We will discuss it next.

Predict the output of the following regex:
RegEx: (var|let)\s[a-zA-Z0-9_]\w* =\s"?\w+"?;
Text: var carname = "volvo"; console.log(carname); let age = 8; var date = "23-03-2020";

Answer: