Javascript. Regular expressions. Part three

Home » Tutorials » JavaScript » Javascript. Regular expressions. Part three
In this lesson we’ll continue to learn regular expressions.We’ll talk about quantifiers and two search modes – greedy and lazy. If you didn’t see last lessons, I recommend you to watch it:
here и here.
Quantifiers in regular expressions are written as {n}, where n is count of symbols for searching. Besides we considered some service symbols, which can be written through quantifiers

? – {0,1} – zero or one.
* – {,} – zero or more than zero
. – any symbol

Notice: in patternFive example I said search was continuing to the string end. But result was href and class attributes (it was correct).
I forgot to mention with “greedy” search in our example “any symbol” condition was satisfied to the string end, but quote was not found. That’s why pattern “went back”, searched quote. That’s why we have got such result.

Code lesson

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
      <script type="text/javascript">
        // Квантификаторы
        // {n}, где n - кол-во символов

        // var pattern = /\w\w\w/
        var pattern = /\w{3}/;
        var patternTwo = /\w{3,10}/;

        // ? = {0,1} - нуль или один
        // * = {0,} - нуль или более
        // . - любой символ

        var str = "Каиль камиль kamil";

        var patternThree = /кам?иль/ig;
        var patternFour = /кам*иль/ig;

        console.log(str.match(patternThree));
        console.log(str.match(patternFour));

        //  жадный и ленивый режим

        var link = '<a href="http://kamil-abzalov.ru" class="test"></a>';

        var patternFive = /href=".+"/gi; //жадный поиск
        var patternSix = /href=".+?"/gi; // ленивый поиск
        var patternSeven = /href="[^"]+"/gi; // аналог жадного

        console.log(link.match(patternFive));
        console.log(link.match(patternSix));
        console.log(link.match(patternSeven));


        /*В качестве разминки написать и проверить шаблон для поиска:

        1. Десятичная дробь
        2. Дата формата (10.07.2016)
        3. Поиск заголовков h1-h6 в строке

        */



      </script>
  </body>
</html>

0 Comments

Submit a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This