Регулярные выражения javascript все флаги

Patterns and flags

Regular expressions are patterns that provide a powerful way to search and replace in text.

In JavaScript, they are available via the RegExp object, as well as being integrated in methods of strings.

Regular Expressions

A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional flags.

There are two syntaxes that can be used to create a regular expression object.

regexp = new RegExp("pattern", "flags");

And the “short” one, using slashes «/» :

regexp = /pattern/; // no flags regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)

Slashes /. / tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.

In both cases regexp becomes an instance of the built-in RegExp class.

The main difference between these two syntaxes is that pattern using slashes /. / does not allow for expressions to be inserted (like string template literals with $ <. >). They are fully static.

Slashes are used when we know the regular expression at the code writing time – and that’s the most common situation. While new RegExp is more often used when we need to create a regexp “on the fly” from a dynamically generated string. For instance:

let tag = prompt("What tag do you want to find?", "h2"); let regexp = new RegExp(`>`); // same as // if answered "h2" in the prompt above

Flags

Regular expressions may have flags that affect the search.

There are only 6 of them in JavaScript:

i With this flag the search is case-insensitive: no difference between A and a (see the example below). g With this flag the search looks for all matches, without it – only the first match is returned. m Multiline mode (covered in the chapter Multiline mode of anchors ^ $, flag «m»). s Enables “dotall” mode, that allows a dot . to match newline character \n (covered in the chapter Character classes). u Enables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter Unicode: flag «u» and class \p . y “Sticky” mode: searching at the exact position in the text (covered in the chapter Sticky flag «y», searching at position)

From here on the color scheme is:

Searching: str.match

As mentioned previously, regular expressions are integrated with string methods.

The method str.match(regexp) finds all matches of regexp in the string str .

    If the regular expression has flag g , it returns an array of all matches:

let str = "We will, we will rock you"; alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match)
let str = "We will, we will rock you"; let result = str.match(/we/i); // without flag g alert( result[0] ); // We (1st match) alert( result.length ); // 1 // Details: alert( result.index ); // 0 (position of the match) alert( result.input ); // We will, we will rock you (source string)
let matches = "JavaScript".match(/HTML/); // = null if (!matches.length) < // Error: Cannot read property 'length' of null alert("Error in the line above"); >
let matches = "JavaScript".match(/HTML/) || []; if (!matches.length) < alert("No matches"); // now it works >

Replacing: str.replace

The method str.replace(regexp, replacement) replaces matches found using regexp in string str with replacement (all matches if there’s flag g , otherwise, only the first one).

// no flag g alert( "We will, we will".replace(/we/i, "I") ); // I will, we will // with flag g alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will

The second argument is the replacement string. We can use special character combinations in it to insert fragments of the match:

Symbols Action in the replacement string
$& inserts the whole match
$` inserts a part of the string before the match
$’ inserts a part of the string after the match
$n if n is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter Capturing groups
$ inserts the contents of the parentheses with the given name , more about it in the chapter Capturing groups
$$ inserts character $
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript

Testing: regexp.test

The method regexp.test(str) looks for at least one match, if found, returns true , otherwise false .

let str = "I love JavaScript"; let regexp = /LOVE/i; alert( regexp.test(str) ); // true

Later in this chapter we’ll study more regular expressions, walk through more examples, and also meet other methods.

Full information about the methods is given in the article Methods of RegExp and String.

Summary

  • A regular expression consists of a pattern and optional flags: g , i , m , u , s , y .
  • Without flags and special symbols (that we’ll study later), the search by a regexp is the same as a substring search.
  • The method str.match(regexp) looks for matches: all of them if there’s g flag, otherwise, only the first one.
  • The method str.replace(regexp, replacement) replaces matches found using regexp with replacement : all of them if there’s g flag, otherwise only the first one.
  • The method regexp.test(str) returns true if there’s at least one match, otherwise, it returns false .

Comments

  • If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
  • If you can’t understand something in the article – please elaborate.
  • To insert few words of code, use the tag, for several lines – wrap them in tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)

Источник

Введение: шаблоны и флаги

Регулярные выражения – мощное средство поиска и замены в строке.

В JavaScript регулярные выражения реализованы отдельным объектом RegExp и интегрированы в методы строк.

Регулярные выражения

Регулярное выражение (оно же «регэксп», «регулярка» или просто «рег»), состоит из шаблона (также говорят «паттерн») и необязательных флагов.

Существует два синтаксиса для создания регулярного выражения.

regexp = new RegExp("шаблон", "флаги");

…И короткий синтаксис, использующий слеши «/» :

regexp = /шаблон/; // без флагов regexp = /шаблон/gmi; // с флагами gmi (будут описаны далее)

Слеши /. / говорят JavaScript о том, что это регулярное выражение. Они играют здесь ту же роль, что и кавычки для обозначения строк.

Регулярное выражение regexp в обоих случаях является объектом встроенного класса RegExp .

Основная разница между этими двумя способами создания заключается в том, что слеши /. / не допускают никаких вставок переменных (наподобие возможных в строках через $ <. >). Они полностью статичны.

Слеши используются, когда мы на момент написания кода точно знаем, каким будет регулярное выражение – и это большинство ситуаций. А new RegExp – когда мы хотим создать регулярное выражение «на лету» из динамически сгенерированной строки, например:

let tag = prompt("Какой тег вы хотите найти?", "h2"); let regexp = new RegExp(`>`); // то же, что // при ответе "h2" на prompt выше

Флаги

Регулярные выражения могут иметь флаги, которые влияют на поиск.

В JavaScript их всего шесть:

i С этим флагом поиск не зависит от регистра: нет разницы между A и a (см. пример ниже). g С этим флагом поиск ищет все совпадения, без него – только первое. m Многострочный режим (рассматривается в главе Многострочный режим якорей ^ $, флаг «m»). s Включает режим «dotall», при котором точка . может соответствовать символу перевода строки \n (рассматривается в главе Символьные классы). u Включает полную поддержку Юникода. Флаг разрешает корректную обработку суррогатных пар (подробнее об этом в главе Юникод: флаг «u» и класс \p ). y Режим поиска на конкретной позиции в тексте (описан в главе Поиск на заданной позиции, флаг «y»)

Здесь и далее в тексте используется следующая цветовая схема:

  • регулярное выражение – красный
  • строка (там где происходит поиск) – синий
  • результат – зелёный

Поиск: str.match

Как уже говорилось, использование регулярных выражений интегрировано в методы строк.

Метод str.match(regexp) для строки str возвращает совпадения с регулярным выражением regexp .

У него есть три режима работы:

    Если у регулярного выражения есть флаг g , то он возвращает массив всех совпадений:

let str = "Любо, братцы, любо!"; alert( str.match(/любо/gi) ); // Любо,любо (массив из 2х подстрок-совпадений)
let str = "Любо, братцы, любо!"; let result = str.match(/любо/i); // без флага g alert( result[0] ); // Любо (первое совпадение) alert( result.length ); // 1 // Дополнительная информация: alert( result.index ); // 0 (позиция совпадения) alert( result.input ); // Любо, братцы, любо! (исходная строка)
let matches = "JavaScript".match(/HTML/); // = null if (!matches.length) < // Ошибка: у null нет свойства length alert("Ошибка в строке выше"); >
let matches = "JavaScript".match(/HTML/) || []; if (!matches.length) < alert("Совпадений нет"); // теперь работает >

Замена: str.replace

Метод str.replace(regexp, replacement) заменяет совпадения с regexp в строке str на replacement (все, если есть флаг g , иначе только первое).

// без флага g alert( "We will, we will".replace(/we/i, "I") ); // I will, we will // с флагом g alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will

В строке замены replacement мы можем использовать специальные комбинации символов для вставки фрагментов совпадения:

Спецсимволы Действие в строке замены
$& вставляет всё найденное совпадение
$` вставляет часть строки до совпадения
$’ вставляет часть строки после совпадения
$n если n это 1-2 значное число, вставляет содержимое n-й скобочной группы регулярного выражения, больше об этом в главе Скобочные группы
$ вставляет содержимое скобочной группы с именем name , также изучим в главе Скобочные группы
$$ вставляет символ «$»
alert( "Люблю HTML".replace(/HTML/, "$& и JavaScript") ); // Люблю HTML и JavaScript

Проверка: regexp.test

Метод regexp.test(str) проверяет, есть ли хоть одно совпадение, если да, то возвращает true , иначе false .

let str = "Я ЛюБлЮ JavaScript"; let regexp = /люблю/i; alert( regexp.test(str) ); // true

Далее в этом разделе мы будем изучать регулярные выражения, увидим ещё много примеров их использования, а также познакомимся с другими методами.

Полная информация о различных методах дана в главе Методы RegExp и String.

Итого

  • Регулярное выражение состоит из шаблона и необязательных флагов: g , i , m , u , s , y .
  • Без флагов и специальных символов, которые мы изучим позже, поиск по регулярному выражению аналогичен поиску подстроки.
  • Метод str.match(regexp) ищет совпадения: все, если есть флаг g , иначе только первое.
  • Метод str.replace(regexp, replacement) заменяет совпадения с regexp на replacement : все, если у регулярного выражения есть флаг g , иначе только первое.
  • Метод regexp.test(str) возвращает true , если есть хоть одно совпадение, иначе false .

Источник

Читайте также:  Python counter to dict
Оцените статью