Регулярные выражения в javascript: примеры использования и сервисы для проверки

Алан-э-Дейл       10.03.2024 г.

The exec function

The executes a search for a match in a specified string. It
returns an object with information about the match.

exec_fun.js

let words = ;

let pattern = /book/;

words.forEach(word => {

    let res = pattern.exec(word);

    if (res) {
        console.log(`${res} matches ${res.input} at index: ${res.index}`);
    }
});

In the example, we apply the pattern on the input strings with .

if (res) {
    console.log(`${res} matches ${res.input} at index: ${res.index}`);
}

We print the information about the match. It includes the index where
the match begins.

$ node exec_fun.js
book matches book at index: 0
book matches bookworm at index: 0
book matches bookish at index: 0
book matches cookbook at index: 4
book matches bookstore at index: 0
book matches pocketbook at index: 6

Wrapping Up

ES2018 continues the work of previous editions of ECMAScript by making regular expressions more useful. New features include lookbehind assertion, named capture groups, () flag, and Unicode property escapes. Lookbehind assertion allows you to match a pattern only if it is preceded by another pattern. Named capture groups use a more expressive syntax compared to regular capture groups. The () flag changes the behavior of the dot () metacharacter to match line break characters. Finally, Unicode property escapes provide a new type of escape sequence in regular expressions.

When building complicated patterns, it’s often helpful to use a regular-expressions tester. A good tester provides an interface to test a regular expression against a string and displays every step taken by the engine, which can be especially useful when trying to understand patterns written by others. It can also detect syntax errors that may occur within your regex pattern. Regex101 and RegexBuddy are two popular regex testers worth checking out.

Do you have some other tools to recommend? Share them in the comments!

(dm, il)

str.replace(str|regexp, str|func)

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

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

Хотя есть подводный камень.

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

Вы можете видеть это в приведённом выше примере: только первый заменяется на .

Чтобы найти все дефисы, нам нужно использовать не строку , а регулярное выражение с обязательным флагом :

Второй аргумент – строка замены. Мы можем использовать специальные символы в нем:

Спецсимволы Действие в строке замены
вставляет
вставляет всё найденное совпадение
вставляет часть строки до совпадения
вставляет часть строки после совпадения
если это 1-2 значное число, то вставляет содержимое n-й скобки
вставляет содержимое скобки с указанным именем

Например:

Для ситуаций, которые требуют «умных» замен, вторым аргументом может быть функция.

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

Функция вызывается с аргументами :

  1. – найденное совпадение,
  2. – содержимое скобок (см. главу Скобочные группы).
  3. – позиция, на которой найдено совпадение,
  4. – исходная строка,
  5. – объект с содержимым именованных скобок (см. главу Скобочные группы).

Если скобок в регулярном выражении нет, то будет только 3 аргумента: .

Например, переведём выбранные совпадения в верхний регистр:

Заменим каждое совпадение на его позицию в строке:

В примере ниже две скобки, поэтому функция замены вызывается с 5-ю аргументами: первый – всё совпадение, затем два аргумента содержимое скобок, затем (в примере не используются) индекс совпадения и исходная строка:

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

Или, если мы используем именованные группы, то объект с ними всегда идёт последним, так что можно получить его так:

Использование функции даёт нам максимальные возможности по замене, потому что функция получает всю информацию о совпадении, имеет доступ к внешним переменным и может делать всё что угодно.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sinh()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
Modifiers:
g
i
m
Groups:

(x|y)
Metacharacters:
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx
Quantifiers:
+
*
?
{X}
{X,Y}
{X,}
$
^
?=
?!
Properties:
constructor
global
ignoreCase
lastIndex
multiline
source
Methods:
compile()
exec()
test()
toString()

JS Statements
break
class
const
continue
debugger
do…while
for
for…in
for…of
function
if…else
let
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

search()

Отдаёт расположение первого совпадения строки  в заданной строке.

Этот метод отдаёт индекс начала упоминания или , если такого не было найдено.

Вы можете использовать регулярные выражения (и на самом деле, даже если вы передаёте строку, то внутренне оно тоже применяется как регулярное выражение).

slice()

Отдает новую строку, которая является частью строки на которой применялся метод, от позиций  до .

Оригинальная строка не изменяется.

 опциональна.

Если вы выставите первым параметром отрицательное число, то начальный индекс будет считаться с конца и второй параметр тоже должен быть отрицательным, всегда ведя отсчет с конца:

JavaScript regex email example

let emails = ;

let pattern = /^+@+\.{2,18}$/;

emails.forEach(email => {
    if (pattern.test(email)) {

        console.log(`${email} matches`);
    } else {

        console.log(`${email} does not match`);
    }
})

This example provides one possible solution.

let pattern = /^+@+\.{2,18}$/;

The fourth part is the dot character; it is preceded by the escape character (\)
to get a literal dot.

The final part is the top level domain name: . Top
level domains can have from 2 to 18 characters, such as sk, net, info, travel,
cleaning, travelinsurance. The maximum lenght can be 63 characters, but most
domain are shorter than 18 characters today. There is also a dot character. This
is because some top level domains have two parts; for instance co.uk.

$ node emails.js
luke@gmail.com matches
andy@yahoocom does not match
34234sdfa#2345 does not match
f344@gmail.com matches

In this tutorial, we have covered regular expressions in JavaScript.

List .

charAt in javascript

The charAt() string method in javascript returns a character at the specific index of the given string.

The method takes the index value as an argument and returns the corresponding character from the calling string.

An index value of a string starts with 0, which means the first character has an index value of 0, the second character has an index value of 1, and so on.

Example

Try It
Run Here

The default index value in the charAt method is 0.

If the index value is out of range then it returns an empty string (»).

If the index can not be converted to an integer then this method returns the first character of the string.

Example

Run Here

# Altenative way to charAt() method

You can consider the string as an array of characters and call out any character of the string by its index value, as all the characters are a member of the array.

Example

Run Here

Window

Window Object
alert()
atob()
blur()
btoa()
clearInterval()
clearTimeout()
close()
closed
confirm()
console
defaultStatus
document
focus()
frameElement
frames
history
getComputedStyle()
innerHeight
innerWidth
length
localStorage
location
matchMedia()
moveBy()
moveTo()
name
navigator
open()
opener
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
print()
prompt()
resizeBy()
resizeTo()
screen
screenLeft
screenTop
screenX
screenY
scrollBy()
scrollTo()
scrollX
scrollY
sessionStorage
self
setInterval()
setTimeout()
status
stop()
top

Window Console
assert()
clear()
count()
error()
group()
groupCollapsed()
groupEnd()
info()
log()
table()
time()
timeEnd()
trace()
warn()

Window History
back()
forward()
go()
length

Window Location
assign()
hash
host
hostname
href
origin
pathname
port
protocol
reload()
replace()
search

Window Navigator
appCodeName
appName
appVersion
cookieEnabled
geolocation
javaEnabled()
language
onLine
platform
product
taintEnabled()
userAgent

Window Screen
availHeight
availWidth
colorDepth
height
pixelDepth
width

Functions #

Functions are called by entering their name, followed by zero or more
arguments enclosed by parentheses. All available functions are listed on the
page Functions.

New functions can be defined by “assigning” an expression to a function call
with one or more variables. Such function assignments are limited: they can
only be defined on a single line.

Note that these function assignments do not create closures; put another way,
all free variables in mathjs are dynamic:

It is however possible to pass functions as parameters:

Math.js itself heavily uses typed functions, which ensure correct inputs and
throws meaningful errors when the input arguments are invalid. One can create
a typed-function in the
expression parser like:

Устаревший способ сделать то же самое

Наиболее распространенный подход — наблюдать за событием , которое возникает при изменениях размеров окна и проверять и/или .

Событие очень много раз вызывается при изменении размеров окна браузера, это — дорогостоящая операция.

Сравнение производительности и для пустой страницы.

В консоли это будет нагляднее, можно посмотреть и сравнить количество вызовов callback-функций для событий из и

Даже если не обращать внимания на проблемы с производительностью, отслеживание только изменений размеров окна () сильно ограничено и не позволяет определять тип устройства (принтер, телевизор), ориентацию экрана. Таким образом, использование даёт больше возможностей в определении состояния html-страницы, чем информация только о его размерах при использовании .

Instance Properties

dotAll : Boolean  readonly

if the was created with the flag. DotAll s will match any character for including new lines ( or ) which do not match by default. Another option is to replace with an empty inverted character class match for systems that do not support ECMAScript 2018. See also .

var str = ‘»a quote\nover multiple lines»‘;

// The following fails because . does not match \n without the s suffix
console.log(/».*»/.test(str));

// The s suffix allows . to match \n
console.log(/».*»/s.test(str));

// Alternatively, use the empty inverted character class
console.log(/»*»/.test(str));

ECMAScript 2018

flags : String  readonly

Returns the flags specified when constructing . Each character in represents a different option of the RegExp. is for . is for . is for . is for . is for .

console.log(/./gim.flags);

global : Boolean  readonly

if the was created with the flag. Global s will match each place occurs in the string, not just the first match. See also .

console.log(‘abcba’.replace(/b/, ‘X’));
console.log(‘abcba’.replace(/b/g, ‘X’));

ignoreCase : Boolean  readonly

if the was created with the flag. IgnoreCase s will do case insensitive matching.

console.log(/hello/.test(‘Hello’));
console.log(/hello/i.test(‘Hello’));

lastIndex : Number

The starting index into the string for the next search. If is , the match must be found starting exactly at . is automatically set to the found index after a successful match. This property only applies if the is or %%#sticky|.

var regexp = /foo|bar|baz/g;
console.log(regexp.exec(‘foo bar baz’));
console.log(regexp.lastIndex);
regexp.lastIndex = 5;
console.log(regexp.exec(‘foo bar baz’));

multiline : Boolean  readonly

if the was created with the flag. Multiline s will match to the beginning of lines as well as the beginning of the string and match to the end of lines as well as the end of the string. Note that does not affect the character class. See for more details.

var str = ‘hello\nworld’;
console.log(/^world/.test(str));
console.log(/^world/m.test(str));

source : String  readonly

The pattern of this regular expression.

JavaScript Regular Expression Methods

As mentioned above, you can either use  or regular expression literal to create a RegEx in JavaScript.

In JavaScript, you can use regular expressions with methods:  and .

There are also some string methods that allow you to pass RegEx as its parameter. They are: , , , and .

Method Description
Executes a search for a match in a string and returns an array of information. It returns null on a mismatch.
Tests for a match in a string and returns true or false.
Returns an array containing all the matches. It returns null on a mismatch.
Returns an iterator containing all of the matches.
Tests for a match in a string and returns the index of the match. It returns -1 if the search fails.
Searches for a match in a string and replaces the matched substring with a replacement substring.
Break a string into an array of substrings.

Regular expression

In JavaScript, we build regular expressions either with slashes
or object.

A pattern is a regular expression that defines the text we are
searching for or manipulating. It consists of text literals and metacharacters.
Metacharacters are special characters that control how the regular expression is
going to be evaluated. For instance, with we search for white
spaces.

After we have created a pattern, we can use one of the functions to apply the
pattern on a text string. The funcions include ,
, , , and
.

The following table shows some regular expressions:

Regex Meaning
Matches any single character.
Matches the preceding element once or not at all.
Matches the preceding element once or more times.
Matches the preceding element zero or more times.
Matches the starting position within the string.
Matches the ending position within the string.
Alternation operator.
Matches a or b, or c.
Range; matches a or b, or c.
Negation, matches everything except a, or b, or c.
Matches white space character.
Matches a word character; equivalent to

Классы символов

Квадратные скобки, окружающие шаблон символов, называются классом символов, например . Класс символов всегда соответствует одному символу из списка указанных символов, что означает, что выражение соответствует только символу a, b или c.

Также могут быть определены классы отрицательных символов, которые соответствуют любому символу, кроме указанных в скобках. Класс отрицанных символов определяется путем размещения символа вставки () сразу после открывающей скобки, например , который соответствует любому символу, кроме a, b и c.

Вы также можете определить диапазон символов, используя символ дефиса () внутри класса символов, например . Давайте посмотрим на некоторые примеры классов:

RegExp Что оно делает
Соответствует любому из символов a, b или c.
Соответствует любому одному символу, кроме a, b или c.
Соответствует любому символу от строчной буквы a до строчной буквы z.
Соответствует любому символу от прописных букв A до прописных букв Z.
Соответствует любому символу от строчной буквы a до прописной буквы Z.
Соответствует одной цифре от 0 до 9.
Соответствует одному символу между a и z или между 0 и 9.

В следующем примере показано, как определить, существует ли шаблон в строке или нет, используя регулярное выражение с методом JavaScript :

Кроме того, вы можете добавить к регулярному выражению, чтобы найти все совпадения в строке:

Регулярные выражения не являются исключительными для JavaScript. Такие языки, как Java, Perl, Python, PHP и т. д., используют одинаковые обозначения для поиска шаблонов в тексте.

Recommended JavaScript Posts:

Recommended:-JavaScript: Array Methods

Recommended:-Comparing Two Arrays in JavaScript Returning Differences

Recommended:-JavaScript Array filter| Filtering Items From Array

Recommended:-JavaScript Array Slice() | Extract Elements From Array

Recommended:-JavaScript Array Contains | Array include() Mehtod

Recommended:-JavaScript Array findIndex | Find First Occurrence Index of Array

Recommended:-JavaScript Array map | Iterate Array Element

Recommended:-JavaScript Array Reduce | Reduce Array to Single Value

Recommended:-JavaScript Array splice() Method By Example

Recommended:-Sorting Using JavaScript Array Sort() Method

Recommended:-JavaScript: Clone an Array & Object By Examples

Recommended:-Remove First, last, or specific Element From Array Javascript

Recommended:-javaScript Push Array, Items Into Array Example

Recommended:-Convert Array to Comma-Separated String javaScript

Recommended:-Convert Array to JSON Object JavaScript

Recommended:-How to Get Only Unique Values From Array in JavaScript

Recommended:-Convert String to Array JavaScript

Recommended:-JavaScript Check the Object | isArray() Function

Recommended:-JavaScript: Array Methods

Recommended:-JavaScript Arrow Functions | More Concise JS Function

Recommended:-JavaScript Window Location | javaScript Window

Recommended:-JavaScript Cookies – Get, Create, Read, Delete

Recommended:-javaScript Resize Image Example

If you have any queries or doubts on how to get match elements from two arrays in JavaScript, you can contact us using the comment box.

Описание

Если метод match не находит совпадений, то он возвращает null. Если совпадение найдено, то метод match возвращает массив с результатами, а свойства глобального объекта RegExp обновляются в соответствии с результатами поиска.

У массива, который возвращает метод match, есть три свойства: input, index и lastIndex. Свойство input содержит строку поиска. Свойство index содержит позицию совпавшей подстроки в строке поиска. Свойство lastIndex содержит позицию символа, который идет за последним совпавшим в строке поиска.

Если глобальный флаг g не установлен, то нулевой элемент массива содержит полное совпадение, в то время как другие элементы содержат все неполные совпадения. Такое поведение похоже на то, как работает метод exec, когда глобальный флаг не установлен. Если же глобальный флаг установлен, то в массиве, начиная с нулевого элемента, содержатся все возможные совпадения.

Метод применяется к объекту: String Object (Windows Scripting — JScript).

Multiline mode — m

The flag stands for multiline mode and serves to make the boundary tokens and match the beginning and end of each line.

By default, the and characters in an expression match the beginning and ending boundaries of a given test string. But with the flag in place, they instead do this for every line in the string.

In the previous section, we saw how the s flag serves to put a regular expression into single line mode, where a given test string is treated as one single line of characters. To many of you, multiline mode would seem to be the opposite of this — a given test string is treated as a sequence of multiple lines of characters.

However this is NOT the case. In fact, treating a string as a sequence of multiple lines of characters is the default behaviour of a regular expression.

Why would a flag do something that’s already there by default?

The single-line and multiline modes set up by the flags s and m respectively, have nothing to do with one another. This usually complicates developers.

The flag targets the wildcard character and makes it match everything. In contrast, the flag target the and characters, and makes them match the start and end of each line respectively.

treats a string as one single line so that the dot can match everything, even newlines. Similarly, treats a string as a sequence of multiple lines so that and can match the begining and ending positions of each line.

Consider the example below:

Construct an expression to match all lines in a given string, that begin with an .

To fully understand this example, you’ll first need to learn about JavaScript Regex Quantifiers and JavaScript Regex Boundaries.

The expression to solve this problem is .

The character matches the start of every line, thanks to the flag. Altogether the expression looks for an at the beginning of every line and if one is found, it matches the whole line, till the end.

The global flag here gets the expression to search for all such lines that begin with an .

str.matchAll(regexp)

Новая возможность

Эта возможность была добавлена в язык недавно.
В старых браузерах может понадобиться полифил.

Метод – «новый, улучшенный» вариант метода .

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

У него 3 отличия от :

  1. Он возвращает не массив, а перебираемый объект с результатами, обычный массив можно сделать при помощи .
  2. Каждое совпадение возвращается в виде массива со скобочными группами (как без флага ).
  3. Если совпадений нет, то возвращается не , а пустой перебираемый объект.

Пример использования:

При переборе результатов в цикле вызов , разумеется, не нужен.

Metacharacters

A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

For instance, you can search for a large sum of money using the ‘\d’ metacharacter: /(+)000/, Here \d will search for any string of numerical character.

The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.

Sr.No. Character & Description
1

.

a single character

2

\s

a whitespace character (space, tab, newline)

3

\S

non-whitespace character

4

\d

a digit (0-9)

5

\D

a non-digit

6

\w

a word character (a-z, A-Z, 0-9, _)

7

\W

a non-word character

8

a literal backspace (special case).

9

matches a single character in the given set

10

matches a single character outside the given set

11

(foo|bar|baz)

matches any of the alternatives specified

How to use the .replaceAll() method

Just like how has a newer method, has a newer method.

The only real difference between and is that you need to use the global search flag if you use a regular expression with :

The real benefit with is that it’s a bit more readable, and replaces all matched patterns when you pass it a string as the first argument.

That’s it! Now you know the basics of matching and replacing parts of strings with regex and some built-in JS methods. These were pretty simple examples, but I hope it still showed how powerful even a little bit of regex can be.

Was this helpful? How do you use the , , , and methods? Let me know over on .

Operators #

The expression parser has operators for all common arithmetic operations such
as addition and multiplication. The expression parser uses conventional infix
notation for operators: an operator is placed between its arguments.
Round parentheses can be used to override the default precedence of operators.

The following operators are available:

Operator Name Syntax Associativity Example Result
, Grouping None
, Matrix, Index None
, Object None
Parameter separator Left to right
Property accessor Left to right
Statement separator Left to right
Row separator Left to right
Statement separator Left to right
Add Left to right
Unary plus Right to left
Subtract Left to right
Unary minus Right to left
Multiply Left to right
Element-wise multiply Left to right
Divide Left to right
Element-wise divide Left to right
Percentage None
Addition with Percentage Left to right
Subtraction with Percentage Left to right
Modulus Left to right
Power Right to left
Element-wise power Right to left
Transpose Left to right
Factorial Left to right
Bitwise and Left to right
Bitwise not Right to left
Bitwise or Left to right
Bitwise xor Left to right
Left shift Left to right
Right arithmetic shift Left to right
Right logical shift Left to right
Logical and Left to right
Logical not Right to left
Logical or Left to right
Logical xor Left to right
Assignment Right to left
Conditional expression Right to left
Range Right to left
, Unit conversion Left to right
Equal Left to right
Unequal Left to right
Smaller Left to right
Larger Left to right
Smallereq Left to right
Largereq Left to right

Introduction

In the previous chapter we got a fairly decent introduction to the syntax of a regular expression in JavaScript, and it is now that we will take it on from there to explore the bits and pieces in more detail.

In this chapter we shall begin with an understanding of what are flags in the world of regular expressions and how they can be used to modify the searching behaviour of given patterns. Once we’re done, we’ll test our skills at JavaScript Regex Flags Quiz.

Of all the flags detailed here, you’ll find only the and flags to be easily understandable, since the others require concepts that we’ll learn later in this tutorial.

Anyways, let’s dive right into it.

regexp.exec(str)

Метод ищет совпадение с в строке . В отличие от предыдущих методов, вызывается на регулярном выражении, а не на строке.

Он ведёт себя по-разному в зависимости от того, имеет ли регулярное выражение флаг .

Если нет , то возвращает первое совпадение в точности как . Такое поведение не даёт нам ничего нового.

Но если есть , то:

  • Вызов возвращает первое совпадение и запоминает позицию после него в свойстве .
  • Следующий такой вызов начинает поиск с позиции , возвращает следующее совпадение и запоминает позицию после него в .
  • …И так далее.
  • Если совпадений больше нет, то возвращает , а для устанавливается значение .

Таким образом, повторные вызовы возвращают одно за другим все совпадения, используя свойство для отслеживания текущей позиции поиска.

В прошлом, до появления метода в JavaScript, вызов в цикле использовали для получения всех совпадений с их позициями и группами скобок в цикле:

Это работает и сейчас, хотя для современных браузеров , как правило, удобнее.

Мы можем использовать для поиска совпадения, начиная с нужной позиции, если вручную поставим .

Например:

Если у регулярного выражения стоит флаг , то поиск будет вестись не начиная с позиции , а только на этой позиции (не далее в тексте).

В примере выше заменим флаг на . Ничего найдено не будет, поскольку именно на позиции слова нет:

Это удобно в тех ситуациях, когда мы хотим «прочитать» что-то из строки по регулярному выражению именно на конкретной позиции, а не где-то далее.

matchAll in javascript

The matchAll() string method in javascript is an improved variant of the match() method.

In the match method when the regular expression is used without the g flag then it works fine but with the g flag, it only returns the matches and not its capturing group.

But the matchAll() method finds all the matching string with its capturing group against the regular expression.

Instead of returning an array the matchAll() method returns an iterator to all results matching the string. You will have to explicitly convert it to array using sperad operator () or using Array.from() method.

Note: It is compulsory to use g flag with the matchAll() method.

Example

Try It
Run Here

Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

Sr.No. Expression & Description
1

Any one character between the brackets.

2

Any one character not between the brackets.

3

It matches any decimal digit from 0 through 9.

4

It matches any character from lowercase a through lowercase z.

5

It matches any character from uppercase A through uppercase Z.

6

It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range to match any decimal digit ranging from 0 through 3, or the range to match any lowercase character ranging from b through v.

Выводы, рецепты

Будет намного проще понять методы JavaScript RegExp, если мы разделим их по использованию на практике.

Чтобы найти только первое совпадение:

  • Найти позицию первого совпадения – str.search(reg);
  • Найти полное совпадение – str.match(reg);
  • Проверить, есть ли совпадение – regexp.test(str);
  • Найти совпадение с заданной позиции – regexp.exec(str), установите regexp.lastIndex в номер позиции.

Чтобы найти все совпадения:

  • Массив совпадений – str.match(reg), регулярное выражение с флагом g;
  • Получить все совпадения с полной информацией о каждом из них – regexp.exec(str) с флагом g в цикле.

Чтобы найти и заменить:

Заменить одну строку на другую или результат работы функции – str.replace(reg, str|func).

Чтобы разделить строку:

str.split(str|reg).

Кроме этого мы изучили два флага JavaScript RegExp:

  • Флаг g — чтобы найти все совпадения (глобальный поиск);
  • Флаг y — чтобы искать на точно заданной позиции внутри текста.

Теперь мы знаем методы и можем использовать регулярные выражения.

КККонстантин Кондрусинавтор статьи «Methods of RegExp and String»

Гость форума
От: admin

Эта тема закрыта для публикации ответов.