D
D
Dmitry2020-05-07 10:58:51
Regular Expressions
Dmitry, 2020-05-07 10:58:51

What means ".*?"?

Hello, there is an expression in js:

function isHTML(str) {
   return /<(br|img).*?>\b|<(a|div).*?<\/\2>/i.test(str);
}


<- this is the opening brace of the tag
(br|img)- this is what comes immediately after the opening brace - the name of the tag - either br or img
.- (decimal point) matches any character except a newline.
*- means zero or more occurrences of the previous character)
?- Means "zero or one". Same as {0,1}. Essentially, makes the character optional.
>- this is the closing bracket of the tag
That is, it will find single tags brand imgin which any character (.), in any number (*) comes after the tag name, but these characters after the tag name are not required (?)

In the second part, it looks for paired tags <aor div. Here, at first and at the end, everything is the same:
<- this is the opening bracket of the tag
(a|div)- this is what comes immediately after the opening bracket - the name of the tag - either br or img
.- (decimal point) matches any character except a line break.
*- means zero or more occurrences of the previous character)
?- Means "zero or one". Same as {0,1}. Essentially, makes the character optional. - what does this part mean? is the closing bracket of the Thank you tag.

<\/\2

>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-05-07
@ddimonn8080

There are detailed explanations here in the sidebar: https://regex101.com/r/ZREAov/1
.*? These symbols should be considered together. They mean "any character in any quantity, but not greedily". In this case, "not greedy" means "until you meet >".
<\/\2Tag closing bracket, slash and value from the second saved group. In this case - (a|div)if the value was contained in the opening tag.
PS If you have this JS executed in the browser, then it is much more correct to use the DOM API instead of the regular expression (I don’t know, maybe it was brought to Node as well).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question