Введение: шаблоны и флаги
Регулярные выражения – мощное средство поиска и замены в строке.
В 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 .
Regular expressions
A regular expression (regex for short) allow developers to match strings against a pattern, extract submatch information, or simply test if the string conforms to that pattern. Regular expressions are used in many programming languages, and JavaScript’s syntax is inspired by Perl.
You are encouraged to read the regular expressions guide to get an overview of the available regex syntaxes and how they work.
Description
Regular expressions are a important concept in formal language theory. They are a way to describe a possibly infinite set of character strings (called a language). A regular expression, at its core, needs the following features:
- A set of characters that can be used in the language, called the alphabet.
- Concatenation: ab means «the character a followed by the character b «.
- Union: a|b means «either a or b «.
- Kleene star: a* means «zero or more a characters».
Assuming a finite alphabet (such as the 26 letters of the English alphabet, or the entire Unicode character set), all regular languages can be generated by the features above. Of course, many patterns are very tedious to express this way (such as «10 digits» or «a character that’s not a space»), so JavaScript regular expressions include many shorthands, introduced below.
Note: JavaScript regular expressions are in fact not regular, due to the existence of backreferences (regular expressions must have finite states). However, they are still a very useful feature.
Creating regular expressions
A regular expression is typically created as a literal by enclosing a pattern in forward slashes ( / ):
Regular expressions can also be created with the RegExp() constructor:
const regex2 = new RegExp("ab+c", "g");
They have no runtime differences, although they may have implications on performance, static analyzability, and authoring ergonomic issues with escaping characters. For more information, see the RegExp reference.
Regex flags
Flags are special parameters that can change the way a regular expression is interpreted or the way it interacts with the input text. Each flag corresponds to one accessor property on the RegExp object.
Flag | Description | Corresponding property |
---|---|---|
d | Generate indices for substring matches. | hasIndices |
g | Global search. | global |
i | Case-insensitive search. | ignoreCase |
m | Allows ^ and $ to match newline characters. | multiline |
s | Allows . to match newline characters. | dotAll |
u | «Unicode»; treat a pattern as a sequence of Unicode code points. | unicode |
v | An upgrade to the u mode with more Unicode features. | unicodeSets |
y | Perform a «sticky» search that matches starting at the current position in the target string. | sticky |
The sections below list all available regex syntaxes, grouped by their syntactic nature.
Assertions
Assertions are constructs that test whether the string meets a certain condition at the specified position, but not consume characters. Assertions cannot be quantified.
Asserts that the current position is the start or end of input, or start or end of a line if the m flag is set.
Asserts that the current position is followed or not followed by a certain pattern.
Asserts that the current position is preceded or not preceded by a certain pattern.
Asserts that the current position is a word boundary.
Atoms
Atoms are the most basic units of a regular expression. Each atom consumes one or more characters in the string, and either fails the match or allows the pattern to continue matching with the next atom.
Matches a previously matched subpattern captured with a capturing group.
Matches a subpattern and remembers information about the match.
Matches any character in or not in a set of characters. When the v flag is enabled, it can also be used to match finite-length strings.
Matches any character in or not in a predefined set of characters.
Matches a character that may not be able to be conveniently represented in its literal form.
Matches a specific character.
Matches a previously matched subpattern captured with a named capturing group.
Matches a subpattern and remembers information about the match. The group can later be identified by a custom name instead of by its index in the pattern.
Matches a subpattern without remembering information about the match.
Matches a set of characters specified by a Unicode property. When the v flag is enabled, it can also be used to match finite-length strings.
Matches any character except line terminators, unless the s flag is set.
Other features
These features do not specify any pattern themselves, but are used to compose patterns.
Matches any of a set of alternatives separated by the | character.
Matches an atom a certain number of times.
Escape sequences
Escape sequences in regexes refer to any kind of syntax formed by \ followed by one or more characters. They may serve very different purposes depending on what follow \ . Below is a list of all valid «escape sequences»:
Escape sequence | Followed by | Meaning |
---|---|---|
\B | None | Non-word-boundary assertion |
\D | None | Character class escape representing non-digit characters |
\P | < , a Unicode property and/or value, then > | Unicode character class escape representing characters without the specified Unicode property |
\S | None | Character class escape representing non-white-space characters |
\W | None | Character class escape representing non-word characters |
\b | None | Word boundary assertion; inside character classes, represents U+0008 (BACKSPACE) |
\c | A letter from A to Z or a to z | A character escape representing the control character with value equal to the letter’s character value modulo 32 |
\d | None | Character class escape representing digit characters ( 0 to 9 ) |
\f | None | Character escape representing U+000C (FORM FEED) |
\k | A named backreference | |
\n | None | Character escape representing U+000A (LINE FEED) |
\p | < , a Unicode property and/or value, then > | Unicode character class escape representing characters with the specified Unicode property |
\q | Only valid inside v -mode character classes; represents the string to be matched literally | |
\r | None | Character escape representing U+000D (CARRIAGE RETURN) |
\s | None | Character class escape representing whitespace characters |
\t | None | Character escape representing U+0009 (CHARACTER TABULATION) |
\u | 4 hexadecimal digits; or | Character escape representing the character with the given code point |
\v | None | Character escape representing U+000B (LINE TABULATION) |
\w | None | Character class escape representing word characters ( A to Z , a to z , 0 to 9 , _ ) |
\x | 2 hexadecimal digits | Character escape representing the character with the given value |
\0 | None | Character escape representing U+0000 (NULL) |
\ followed by any other digit character becomes a legacy octal escape sequence, which is forbidden in Unicode-aware mode.
In addition, \ can be followed by some non-letter-or-digit characters, in which case the escape sequence is always a character escape representing the escaped character itself:
- \$ , \( , \) , \* , \+ , \. , \/ , \? , \[ , \\ , \] , \^ , < , \| , >: valid everywhere
- \- : only valid inside character classes
- \! , \# , \% , \& , \, , \: , \; , \ < , \= , \>, \@ , \` , \~ : only valid inside v -mode character classes
The other ASCII characters, namely space character, » , ‘ , _ , and any letter character not mentioned above, are not valid escape sequences. In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \a represents the character a . This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.
Specifications
Browser compatibility
BCD tables only load in the browser